关于java:Spring-注入静态对象使用方式

42次阅读

共计 1329 个字符,预计需要花费 4 分钟才能阅读完成。

动态注入要求

  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;}
}

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

正文完
 0