# SpringBoot 初始化 Bean、初始化静态变量

SpringBoot 初始化 Bean、初始化静态变量


SpringBoot 初始化 Bean
@Value 方式初始化
  • people.properties
people.id:1001
people.name:"张三"
people.address:"北京大兴亦庄区"
  • 使用 Value取值,用Bean注解将Bean添加到容器中
@Configuration
@PropertySource(value="classpath:/test/people.properties",encoding = "UTF-8")
public class PeopleBeanOne {

    private static final Logger logger = LoggerFactory.getLogger(PeopleBeanOne.class);

    @Value("${people.id}")
    private String id;

    @Value("${people.name}")
    private String userName;

    @Value("${people.address}")
    private String address;


    @Bean
    public PeopleBeanOne initPeopleBean() {
        PeopleBeanOne people = new PeopleBeanOne();
        people.setId(id);
        people.setUserName(userName);
        people.setAddress(address);
        logger.info("peoplebean info :{}", people);
        return people;
    }
    
    // 省略 set、get 方法
}
prefix 方式初始化
  • application.yml中添加bean的信息
# 测试 prefix 方式注入 bean
people:
  id: 1004
  name: "李四"
  address: "青海省"
  • 配置 属性的前缀("people")
@Configuration
@ConfigurationProperties(prefix = "people")
public class PeopleBeanThree {

    private String id;

    private String userName;

    private String address;
    
    // 省略 set、get 方法
}

参数的方式拿到Spring 中的 Bean set方法中初始化静态变量
  • set()方法中初始化静态变量
@Component
public class RedisClient {

    private static RedissonClient redissonClient;

    @Autowired(required = true)
    public void setRedissonClient(RedissonClient redissonClient){
        RedisClient.redissonClient=redissonClient;
        logger.info("redisclinet注入完成!");
    }

    public static void setList(){
        redissonClient.getList("one").add("two");
    }
}


构造方法 参数的方式拿到Spring 中的 Bean 构造方法中初始化静态变量
private static RedissonClient redissonClientOne;

/**
  * 作为参数拿到 redissonClient 的 Bean
  *
  * @param redissonClient
  */
public InitStaticVariableOne(RedissonClient redissonClient) {
    // 初始化类变量
    redissonClientOne = redissonClient;
}

@PostConstruct方式实现
  • @PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法。这种方式和在xml中配置 init-method和 destory-method方法差不多,定义spring 容器在初始化bean和容器销毁之前的所做的操作。
@Component
public class InitStaticVariableThree {

    private static final Logger logger = LoggerFactory.getLogger(InitStaticVariableThree.class);

    @Autowired
    private RedissonClient redissonClient;

    public static RedissonClient redissonClientOne;

    @PostConstruct
    public void init() {
        redissonClientOne = redissonClient;
        logger.info(String.valueOf(redissonClient));
        logger.info(String.valueOf(redissonClientOne));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全栈程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值