2

静态注入要求

  1. 能被Spring扫描到主类
  2. 能被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;
    }
}

将注入的类,赋值给静态对象上


李晗
27 声望1 粉丝