wubinghuan

spring通过静态方法获得properties文件的值

获得spring bean方法

@Component
public class BeanUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) throws BeansException {
        return applicationContext.getBean(clazz);
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

}

使用value注解注入properties文件中的属性,提供静态访问

@Component
public class Constant {

    @Value("${server}")
    private String server;

    public static Constant bean() {
        return BeanUtils.getBean(Constant.class);
    }

    public String getServer(){
        return server;
    }
}

 

在其它类中就可以使用 Constant.bean().getServer()来获得server属性的值了

posted on 2016-10-14 09:37  wubinghuan  阅读(835)  评论(0编辑  收藏  举报

导航