通过注解方式注入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中。

 

相关文章:

  • 2021-11-03
  • 2021-12-18
  • 2022-12-23
  • 2021-05-24
  • 2021-04-22
  • 2021-10-09
  • 2021-09-30
  • 2021-09-23
猜你喜欢
  • 2021-05-25
  • 2021-10-05
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
  • 2023-02-10
相关资源
相似解决方案