Spring静态注入的核心首先是需要是一个Bean,才可以从Spring上下文中注入Bean,下例中environment是需要Autowired注入的Bean,之所以选择Environment是因为它有Spring已经加载好的属性配置,直接拿来用比从文件中读取更优雅,从文件中读取需要面临jar包外部配置问题,暂时未找到较好解决办法。
@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。此处把PropertiesUtils被Spring实例化的Bean赋值给静态变量tool,后续可以通过tool使用实例化好的PropertiesUtils的Bean。
getProperty作为根据key获取指的静态方法,实现获取配置属性。
@Component public class PropertiesUtils { private static PropertiesUtils tool; @Autowired private Environment environment; public static String getProperty(String property) { return tool.environment.getProperty(property); } @PostConstruct public void init() { tool = this; tool.environment = this.environment; } }
实现Starter关键步骤——配置类,自动配置PropertiesUtils的Bean
public class AutoConfig { @Bean private PropertiesUtils propertiesUtils() { return new PropertiesUtils(); } }
实现Starter关键步骤——在resources的创建META-INF文件夹,创建spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.AutoConfig
Environment :
需要注意的是下边的两个方法都需要工具类创建实例的时候才会注入。所以不建议在工具类注入实例。因为一般工具类都是直接通过类来使用的。
直接上代码
//可以换成@Configuration,与@Inject配合使用 @Componentpublic class XXUtils { //可以换成@Inject/ @Autowired @Resource private XXXProperties xxxPropertiesAutowired; private static XXXProperties xxxProperties; @PostConstruct public void init() { this.xxxPropertiesAutowired = xxxProperties; } }
@Component public class UrlUtil { private static RRJConfig rrjConfig; @Autowired public void setRRJConfig(RRJConfig rRJConfig) { UrlUtil.rrjConfig = rRJConfig; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。