spring常用公共类编写

一、常用配置类获取

1.1:提供spring上下文获取公共类

package com.hdx.hkafka.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware {
 
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

1.2:公共配置类编写

使用:获取name

CommonConfig.getCommonConfig().getName()
package com.hdx.hkafka.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class CommonConfig {

    public String getName() {
        return name;
    }

    @Value("${name:张三}")
    private String name;

    public static CommonConfig getCommonConfig() {
        return Sigleton.commonConfig;
    }

    private static class Sigleton {
        private final static CommonConfig  commonConfig =
                (CommonConfig) SpringUtils.getApplicationContext().getBean("commonConfig");
    }
}

 

posted @ 2022-12-12 22:19  银河系的极光  阅读(40)  评论(0)    收藏  举报