静态注入要求
- 能被Spring扫描到主类
- 能被Spring扫描到注入的类
注入的三种方式
被注入的类
package lihan.properties;
import org.springframework.stereotype.Component;
// 添加注解可以被Spring 扫到
@Component
public class ConfigProperties {
private String aaa = "aaa";
private String bbb = "bbb";
private String ccc = "ccc";
private String ddd = "ddd";
private String eee = "eee";
public String getAaa() {
return aaa;
}
public void setAaa(String aaa) {
this.aaa = aaa;
}
public String getBbb() {
return bbb;
}
public void setBbb(String bbb) {
this.bbb = bbb;
}
public String getCcc() {
return ccc;
}
public void setCcc(String ccc) {
this.ccc = ccc;
}
public String getDdd() {
return ddd;
}
public void setDdd(String ddd) {
this.ddd = ddd;
}
public String getEee() {
return eee;
}
public void setEee(String eee) {
this.eee = eee;
}
}
1. 使用构造器注入
@Component
public class StuStaticConfig {
private static ConfigProperties configProperties;
public StuStaticConfig(ConfigProperties configProperties) {
this.configProperties = configProperties;
}
}
2. set注入
set不能为static静态方法
@Component
public class StuStaticConfig {
private static ConfigProperties configProperties;
@Autowired
public void setConfigProperties(ConfigProperties configProperties) {
StuStaticConfig.configProperties = configProperties;
}
}
3. @PostConstruct 注入
@Component
public class StuStaticConfig {
private static ConfigProperties configProperties;
@Autowired
private ConfigProperties configPropertiesTemp;
@PostConstruct
public void init() {
this.configProperties = this.configPropertiesTemp;
}
}
将注入的类,赋值给静态对象上
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。