简体   繁体   中英

How does spring find bean for Environment?

I have this correct code. And I don't understand how spring find bean for Environment interface. Help me. Thank you

@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;
    }
}

The mechanism is called Dependency Injection and you'll find many articles on the web explaining the concept and Spring-specific details. Basically reflection is used to find an existing bean (instance of an object) in the global Application Context by either the name of the bean or the class.

In this case Spring initializes an Environment instance by default. If a member is annotated with @Autowired and a matching bean exists, it is injected into the AppConfig instance by Spring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM