spring 注解注入bean

通过注解方式注入bean,需要在配置类下注入bean

第一步,配置扫描文件夹

首先要在spring.xml中配置需要扫描的配置类

<context:componenet-scan base-package="com.kylin.config" />

第二步,新建注解配置类

@Configuration
public class RedisConfiguration {
    @Value("${redis.host}")
     private String redisHost;   
     @Value("${redis.port}")
     private String redisPort; 
    

    @Bean(name="jedisPoolConfig")
    public JedisPoolConfig createJedisConfig() {
        JedisPoolConfig jpc = new JedisPoolConfig();
        return jpc;
    }
    
       @DependsOn("jedisPoolConfig")
     @Bean(name="jedisPoolConfig")
    public JedisCluster createJedisCluster(JedisPoolConfig jedisPoolConfig) {
        HostAndPort hap = new HostAndPort(redisHost,redisPort);
        JedisCluster jc = new JedisCluster(hap,jedisPoolConfig);
        return jc;
    }
    
}
        

以redis为例,其中某个bean需要依赖另一个bean的话,需要通过@DependsOn注解,让需要依赖的bean先加载,需要依赖的bean通过方法参数,传入jedisCluster中。

 

posted @ 2020-06-01 16:11  KylinStayHere  阅读(338)  评论(0编辑  收藏  举报