springboot 注入 / 静态注入
- 参数配置:application.properties
sc.crm.upDirPath=
- 注入:
spring boot 的任意组件都能使用,这里声明了一个简单组件 @Component,该注解通常用来定义一些需要配置的常量或者用于注入的工具类,而不用手动去 new 了
@Componentpublic class CrmProperties { @Value("${sc.crm.upDirPath}") private String uploadPath; public String getUploadPath() { return uploadPath; } public void setUploadPath(String uploadPath) { this.uploadPath = uploadPath; }}
- 使用:直接注入
@Servicepublic class CustomerServiceImpl implements CustomerService { @Autowired private CrmProperties crmProperties; //也可以定义为属性/字段直接使用 @Value("${sc.crm.upDirPath}") private String uploadPath; }
- 静态注入:
4.1. 实现 spring 的一个获取上下文的工具类
import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;/** * Spring工具类,获取Spring上下文对象等 */@Componentpublic class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(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().getBean(name); } public staticT getBean(Class clazz){ return getApplicationContext().getBean(clazz); } public static T getBean(String name,Class clazz){ return getApplicationContext().getBean(name, clazz); }}
4.2. 静态注入:
public final class UpDownLoadUtil { private static String uploadPath ; //通过静态代码块,给变量赋值 static{ CrmProperties crmProperties = SpringContextUtil.getBean(CrmProperties.class); uploadPath = crmProperties.getUploadPath(); } //将构造方法私有化,所有静态工具只能通过静态调用 private UpDownLoadUtil(){ throw new AssertionError(); } public static void testUtil(){ systom.out.println(uploadPath); } }
到这里,就可以在静态方法中正常使用该配置常量了
=============== 分割线 ===============
==注意:典型错误示例,这样写虽然不会报错,但是根据类的加载机制,这里不能正确的获取到想要的参数,最后输出只有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);}