SpringBoot 初始化 Bean、初始化静态变量
SpringBoot 初始化 Bean
@Value 方式初始化
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;
}
}
prefix 方式初始化
application.yml
中添加bean
的信息
people:
id: 1004
name: "李四"
address: "青海省"
@Configuration
@ConfigurationProperties(prefix = "people")
public class PeopleBeanThree {
private String id;
private String userName;
private String address;
}
参数的方式拿到Spring 中的 Bean 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;
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));
}
}