spring
xml配置文件 构造器注入setter注入
在JavaConfig中注解注入@Configuration @PropertySource读取属性文件@value@Bean
自动装配@Component @autowire
20.3.19更新
Spring中Bean的理解以及@Bean的作用
“@Bean 用在方法上,告诉Spring容器,你可以从下面这个方法中拿到一个Bean
Spring帮助我们管理Bean分为两个部分,一个是注册Bean,一个装配Bean。
完成这两个动作有三种方式,一种是使用自动配置的方式、一种是使用JavaConfig的方式,一种就是使用XML配置的方式。
- 在自动配置的方式中,使用@Component去告诉Spring,我是一个bean,你要来管理我,然后使用@AutoWired注解去装配Bean(所谓装配,就是管理对象直接的协作关系)。
- 然后在JavaConfig中,@Configuration其实就是告诉spring,spring容器要怎么配置(怎么去注册bean,怎么去处理bean之间的关系(装配))。那么就很好理解了,@Bean的意思就是,我要获取这个bean的时候,你spring要按照这种方式去帮我获取到这个bean。
- 到了使用xml的方式,也是如此。君不见标签就是告诉spring怎么获取这个bean,各种就是手动的配置bean之间的关系。”
springboot属性注入方式
- @autowire属性注入(
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)//声明要使用JdbcProperties这个类的对象
public class JdbcConfiguration {
@Autowired
private JdbcProperties jdbcProperties;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(jdbcProperties.getUrl());
dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
dataSource.setUsername(jdbcProperties.getUsername());
dataSource.setPassword(jdbcProperties.getPassword());
return dataSource;
}
}
- 构造函数注入
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {
private JdbcProperties jdbcProperties;
public JdbcConfiguration(JdbcProperties jdbcProperties){
this.jdbcProperties = jdbcProperties;
}
@Bean
public DataSource dataSource() {
// 略
}
- @ bean注解方法的形参注入(推荐使用)
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {
@Bean
public DataSource dataSource(JdbcProperties jdbcProperties) {
// ...
}
}
- @bean注解方法添加@configurationProperties注解
@Configuration
public class JdbcConfig {
@Bean
// 声明要注入的属性前缀,SpringBoot会自动把相关属性通过set方法注入到DataSource中
@ConfigurationProperties(prefix = "jdbc")//声明当前类为属性读取类
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
return dataSource;
}
}