春天如何为环境找到豆子?

我有这个正确的代码。而且我不了解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;
    }
}
tiantianwlx 回答:春天如何为环境找到豆子?

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

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

本文链接:https://www.f2er.com/3002337.html

大家都在问