Spring如何为环境找到bean?

问题描述 投票:0回答:2

我有这个正确的代码。而且我不了解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;
    }
}
java spring javabeans autowired
2个回答
1
投票

该机制称为Dependency Injection,您会在网上找到许多articles来解释概念和特定于Spring的细节。基本上,反射是通过bean的名称或类在全局Application Context中查找现有的bean(对象的实例)。

在这种情况下,Spring默认情况下会初始化一个Environment实例。如果用@Autowired注释成员,并且存在匹配的bean,则Spring将其注入到AppConfig实例中。


0
投票

该机制称为Dependency Injection,您会在网上找到许多articles来解释概念和特定于Spring的细节。基本上,反射是通过Bean的名称或类在全局Application Context中查找现有的Bean(对象的实例)。

© www.soinside.com 2019 - 2024. All rights reserved.