我有这个正确的代码。而且我不了解spring如何为Environment接口找到bean。帮我。谢谢
@Configuration
@ComponentScan(value = "ru.itis")
@PropertySource("application.properties")
public class AppConfig {
@Autowired
private Environment environment;
@Bean
public NamedParameterJdbcTemplate template() {
return new NamedParameterJdbcTemplate(dataSource());
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getProperty("jdbc.driver"));
dataSource.setUrl(environment.getProperty("jdbc.url"));
dataSource.setUsername(environment.getProperty("jdbc.username"));
dataSource.setPassword(environment.getProperty("jdbc.password"));
return dataSource;
}
}
该机制称为Dependency Injection,您会在网上找到许多articles来解释概念和特定于Spring的细节。基本上,反射是通过bean的名称或类在全局Application Context中查找现有的bean(对象的实例)。
在这种情况下,Spring默认情况下会初始化一个Environment
实例。如果用@Autowired
注释成员,并且存在匹配的bean,则Spring将其注入到AppConfig
实例中。
该机制称为Dependency Injection,您会在网上找到许多articles来解释概念和特定于Spring的细节。基本上,反射是通过Bean的名称或类在全局Application Context中查找现有的Bean(对象的实例)。