首页 > 解决方案 > Spring如何为环境找到bean?

问题描述

我有这个正确的代码。而且我不明白 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;
    }
}

标签: javaspringjavabeansautowired

解决方案


该机制称为依赖注入,您会在网上找到许多解释概念和特定于 Spring 的细节的文章。基本上,反射用于通过 bean 的名称或类的名称在全局应用程序上下文中查找现有的 bean(对象的实例)。

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


推荐阅读