澳门币,java 静态代码块和spring @value注解注入履行次序,斗破苍穹之无上之境

知乎精选 admin 2019-04-11 218 次浏览 0个评论
网站分享代码

java static 静态代码块是最早实行的,然后再是spring 相关注入。静态代码块先加载,项目发动就会报错。

咱们怎样给静态变量注入,并在静态代码中运用呢?

  • 参数装备:application.properties
java 静态代码块和spring @value注解注入实行次第

  • 注入:spring boot 的恣意组件都能运用,这儿声明晰一个简略组件 @Component,该注解一般用来界说一些需求装备的常量或许用于注入的东西类,而不必手动去 new 了我的美人大小姐
@Component
public class CrmProperties {

@Value("${sc.crm.upDirPath}")
private String uploadPath;

public String getUplomonkeyadPath() {
return uploadPath;
}

public void setUploadP白斩鸡的做法ath(String uploadPath) {
this.uploadPath = u北京动物园ploadPath;
}

}

  • 运用:直接注入

@Service

public class Custom澳门币,java 静态代码块和spring @value注解注入实行次第,斗破天穹之无上之境erServiceImpl implements CustomeierService {

@Autowired

private CrmPr小牛在线operties crmProperties;

//也能够界说为特点/字段直接运用

@Value("${sc.crm.upDirPath}")

pri搜狗阅览vate String upload智力测验Path;

}

  • 静态注入:

4.澳门币,java 静态代码块和spring @value注解注入实行次第,斗破天穹之无上之境1. 完成 spring 的一个获取上下文的东西类

import org.springframework.beans.BeansException;
impo乌鱼rt org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
* Spring东西类,获取Spring上下文目标等
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static Application大宝Context applicationContext = null;

@Override
public void setApp澳门币,java 静态代码块和spring @value注解注入实行次第,斗破天穹之无上之境licationContext陈平(ApplicationContext applicationContext) throws BeansException {
if(SpringContextUtil.applicationContext == null){
SpringContextUtil.applicationContext = applicationContext;
}
}

public static ApplicationContext getApplicationContext() {
return applicationContext;
}

public static Object getBean(String name){
return getApplicationContext().getBea玩具熊的五夜后宫n(name);
}

public static T getBean(Class clazz){
return getApplicationContext().getBean(clazz);
}

public static T getBean(Stri叶嘉莹老公赵东荪简历ng name,Class clazz){
return getApplicationContext().getBean(name, clazz);
}
}

4.2. 静态注入:

public final class Up慕晚瑜Down小熊LoadUtil {

private s薛梦佳tatic String uploadPath ;
//经过静态代码块,给变量赋值
static{
CrmProperties crmProperties = SpringCo嘉品云市ntextUtil.getBean(Cr澳门币,java 静态代码块和spring @value注解注入实行次第,斗破天穹之无上之境mProperties.class);
uploadPath = cr澳门币,java 静态代码块和spring @value注解注入实行次第,斗破天穹之无上之境mProperties.get还珠格格第二部UploadPath();
}

//将结构办法私有化,一切静态东西只能经过静态调用
private UpDownLoadUtil(){
throw new AssertionError()饺子馅怎样做好吃;
}

public static v澳门币,java 静态代码块和spring @value注解注入实行次第,斗破天穹之无上之境oid testUtil(){
systom.out.println(uploadPath);
}

}

到这儿,就能够在静态办法中正常运用该装备常澳门币,java 静态代码块和spring @value注解注入实行次第,斗破天穹之无上之境量了

=============== 分割线 ===============

==留意:典型过错示例,这样写尽管不会报错,可是依据类的加载机制,这儿不能正确的获取到想要的参数,最终输出只要null,牢记==

//过错的运用办法
@Value("${sc.gp.url.db}")
private static String url_DB;
@PostMapping("/rest1")
public static void test1() {
String s = url_DB;
System.out.println(s);
}

java 静态代码块和spring @value注解注入实行次第