spring boot 中bean的集中依赖注入方式

在spring boot中,配置xml已经淘汰,所有的配置文件都演变成了java config bean。那么一个java bean中如果依赖其他的java bean,一般常用的有哪几种方式呢。本文中介绍四种常用的依赖注入方式

autowire注解方式

如下面的代码中,在JdbcConfiguration类中,JdbcProperties就是通过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;
    }
​
}

构造函数注入

在JdbcConfiguration类中,我们新仅提供了一个构造函数,切构造函数的参数对象为JdbcProperties对象,那么spring在实例化JdbcConfiguration并注入ioc容器的时候就会调用该构造函数并找到依赖对象jdbcProperties作为参数传递。

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {
​
    private JdbcProperties jdbcProperties;
​
    public JdbcConfiguration(JdbcProperties jdbcProperties){
        this.jdbcProperties = jdbcProperties;
    }
​
    @Bean
    public DataSource dataSource() {
        // 略
    }

bean注解方法的形参注入

类似以往的xml配置文件的的bean配置项,springboot 提供java bean config方式,只要类上声明一个注解@Configuration,那么这个类就是一个配置类,spring 就会扫描这个类,并将这个类中的bean对象注入到ioc(其实这个bean对象就类似xml的bean配置)

如下代码中,DataSource 的注入就是利用了@Bean注解,而DataSource依赖的JdbcProperties就是通过形参实现DataSource的依赖注入的。

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {
​
    @Bean
    public DataSource dataSource(JdbcProperties jdbcProperties) {
        // ...
    }
}

bean注解方法添加@configurationProperties注解

该种方式试用与bean对象中使用了大量的配置属性需要注入的场景,比如在DataSource类中有很多属性是通过配置文件将属性值动态注入的,那么可以通过@ConfigurationProperties注解来实现类属性的依赖注入

@Configuration
public class JdbcConfig {
    
    @Bean
    // 声明要注入的属性前缀,SpringBoot会自动把相关属性通过set方法注入到DataSource中
    @ConfigurationProperties(prefix = "jdbc")//声明当前类为属性读取类
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }
}

评论

公众号:mumuser

企鹅群:932154986

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×