一、Autowired注入方式(以注入连接池为例)
1. 创建一个属性读取类:JdbcProperties
/** * 属性读取类 * prefix: 为application.properties文件中的前缀 */ @ConfigurationProperties(prefix = "jdbc") //读取配置文件,声明一个类是读取配置类 public class JdbcProperties { private String driverClassName; //配置文件中的属性名称 private String url; private String username; private String password; //get、set方法 }
* 在类上通过@ConfigurationProperties注解声明当前类为属性读取类
* prefix="jdbc"
@Configuration //声明一个类为Java配置类,相当于一个xml文件 @EnableConfigurationProperties(JdbcProperties.class) //启用属性读取类 public class JdbcConfiguration { @Autowired private JdbcProperties jdbcProperties; //注入读取类 @Bean //把方法返回值注入到spring容器 public DataSource dataSource(){ DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(this.jdbcProperties.getDriverClassName()); dataSource.setUrl(this.jdbcProperties.getUrl()); dataSource.setUsername(this.jdbcProperties.getUsername()); dataSource.setPassword(this.jdbcProperties.getPassword()); return dataSource; } }
2)构造函数注入
@Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfiguration { private JdbcProperties jdbcProperties; public JdbcConfiguration(JdbcProperties jdbcProperties){ this.jdbcProperties = jdbcProperties; } @Bean public DataSource dataSource() { // 略 } }
3)@Bean方法的参数注入
@Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfiguration { @Bean public DataSource dataSource(JdbcProperties jdbcProperties) { // ... } }
4)
@Configuration public class JdbcConfiguration { @Bean // 声明要注入的属性前缀,SpringBoot会自动把相关属性通过set方法注入到DataSource中 @ConfigurationProperties(prefix = "jdbc") public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); return dataSource; } }