Spring Aware與靜態(tài)方法的使用自動注入

Spring Aware

1、介紹

Spring的依賴注入的最大亮點(diǎn)就是你所以的Bean對Spring容器的存在是沒有意思的。即你可以將你的容器換成別 的容器

在項(xiàng)目中,只有容器存在時,才可以調(diào)用Spring所提供的資源。

@Autowired 用在構(gòu)造函數(shù)上
我們知道@Autowired 注釋,可以對類成員變量、方法及構(gòu)造函數(shù)進(jìn)行標(biāo)注,完成自動裝配的工作,此種方式就是在構(gòu)造函數(shù)上使用@Autowired。

最后會介紹在靜態(tài)方法中注入

2、簡單的示例

程序清單

  1. 一個text文件
  2. 演示的bean,即AwareService
  3. 配置類 AwareConfig 類似于applicationContext.xml
  4. 程序入口,AwareMain
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @description: 依賴注入的使用
 *      繼承之后重新
 *      BeanNameAware 獲取到容器中Bean的名稱
 *      ResourceLoaderAware 獲得記載器
 *      
 * @author: Shenshuaihu
 * @version: 1.0
 * @data: 2019-05-25 00:24
 */
@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware {

    private String beanName;
    private ResourceLoader loader;

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.loader = resourceLoader;
    }

    public void outputResult() {
        System.out.println("Bean的名稱為:" + beanName);
        Resource resource = loader.getResource("classpath:com/ch3/aware/test.txt");

        try {
            System.out.println("加載文件內(nèi)容為:" + IOUtils.toString(resource.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @description:  配置類
 * @author: Shenshuaihu
 * @version: 1.0
 * @data: 2019-05-25 00:35
 */
@Configuration
@ComponentScan("com.ch3.aware")
public class AwareConfig {
}
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @description: 運(yùn)行
 * @author: Shenshuaihu
 * @version: 1.0
 * @data: 2019-05-25 00:36
 */
public class AwareMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(AwareConfig.class);
        AwareService awareService = context.getBean(AwareService.class);
        awareService.outputResult();
        context.close();
    }
}

3、深入理解

在項(xiàng)目中正常情況是直接自動注入的

@Service
public class SpitterUserDetailService implements UserDetailService {

    @Autowired
    public  SpittleRepository spittleRepository;
    
}

或者是

@Service
public class SpitterUserDetailService implements UserDetailService {

    public  SpittleRepository spittleRepository;

    @Autowired
    public void setSpittleRepository(SpittleRepository spittleRepository) {
        this.spittleRepository = spittleRepository;
    }

如果出現(xiàn)靜態(tài)的就尷尬了

4、拓展理解

在項(xiàng)目上,可能是在Utils類中,靜態(tài)方法需要調(diào)用Service 會使用到自動注入,或者靜態(tài)方向需要訪問數(shù)據(jù),咱需要靜態(tài)方法時的注入

@Component
public class HttpUtil {
    private static RedisTemplate redisTemplate;
    /**
     * 注入bean,可以使用靜態(tài)方法
     * @param redisTemplate redis
     */
    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        HttpUtil.redisTemplate = redisTemplate;
    }
    
     public static String postRest(String sysUrl, String tokenParam) {
        String tokenKey = REDIS_KEY_TOKEN + sysUrl;
        /**
         * 每次請求都獲取,改變成從redis中取 獲取token,
         * 如果redis不存在需要重新獲取,如果執(zhí)行失敗了,需要重新獲取
         */
        String token = (String) redisTemplate.opsForValue().get(tokenKey);
        return token;
        }
  }

例子2,參考于其他:

2. 使用 @PostConstruct 注解
@PostConstruct是Java EE 5引入來影響Servlet生命周期的注解,被用來修飾非靜態(tài)的void()方法,@PostConstruct在構(gòu)造函數(shù)之后執(zhí)行,init()方法之前執(zhí)行。

代碼:

@Component
public class PropConfig {
    @Autowired
   private SysConfigService sysConfigService;

   private static PropConfig propConfig;

    @PostConstruct
    public void init() {
        propConfig = this;
        propConfig.sysConfigService = this.sysConfigService;
    }

    public static   Map<String, String> LoadPoperties(String filePath) 
    throws ConfigException {
        List<SysConfig> configs = propConfig.sysConfigService.getSysConfigData();
          return poperties;
        }
}

參考文章
https://blog.51cto.com/zhengjiang/2141118

        2019/05/25凌晨于成都
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容