当一个类实现了这个接口之后,这个类就可以方便地获得 ApplicationContext 中的所有bean。换句话说,就是这个类可以直接获取Spring配置文件中,所有有引用到的bean对象。结合工厂模式写个demo,比如说ApplicationContext 中有两个发送短信的bean,一个是叫移动的Bean,另一个是叫电信的Bean,那么在某一个场景下,你只要用某一个Bean,那么到底用哪一个取决于你自已,也就是你所传的参数。

1.类ChannelFactory实现了ApplicationContextAware接口

package com.tanlu.user.factory;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; @Component
public class ChannelFactory implements ApplicationContextAware {
private static ApplicationContext applicationContext; @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
} /**
* 获取applicationContext
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
} public Object getBean(String param) {
return applicationContext.getBean(param);
} /**
* 通过class获取Bean.
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
} public SendMessageChannel getChannel(String code){
switch (code){
case "1":
return applicationContext.getBean(YiDongMobile.class);
case "2":
return applicationContext.getBean(DianXinMobile.class);
default:
return applicationContext.getBean(YiDongMobile.class);
}
} }

2.ApplicationContext 中的两个Bean

 package com.tanlu.user.factory;

 import com.tanlu.user.model.ResponseData;
import org.springframework.stereotype.Component; @Component
public class DianXinMobile implements SendMessageChannel { @Override
public ResponseData sendMsg(String s1) {
ResponseData data = ResponseData.susscce();
data.setMessage("电信");
System.out.println("中国电信发送短信");
return data;
}
}
 package com.tanlu.user.factory;

 import com.tanlu.user.model.ResponseData;
import org.springframework.stereotype.Component; /**
*移动
*/
@Component
public class YiDongMobile implements SendMessageChannel { @Override
public ResponseData sendMsg(String s1) {
ResponseData data = ResponseData.susscce();
data.setMessage("移动");
System.out.println("我是中国移动发送短信");
return data;
}
}
 package com.tanlu.user.factory;

 import com.tanlu.user.model.ResponseData;

 public interface SendMessageChannel {
/**
* 发送短信
* @param s1
*/
public ResponseData sendMsg(String s1);
}

3.测试,这时候你可以随意注入实现ApplicationContextAware接口的类。

 package com.tanlu.user.controller;

 import com.alibaba.fastjson.JSON;
import com.tanlu.user.factory.ChannelFactory;
import com.tanlu.user.model.ResponseData;
import com.tanlu.user.model.dto.SendMessageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; @RequestMapping("/message")
@RestController
public class SendMessageController {
private static final Logger logger = LoggerFactory.getLogger(SendMessageController.class); @Autowired
private ChannelFactory channelFactory; /**
* 工厂类demo
* @param dto
* @return
* @throws Exception
*/
@RequestMapping(value = "/channel", method = RequestMethod.POST, produces = "application/json")
public ResponseData sendMsgCode(@RequestBody SendMessageDto dto) throws Exception {
String code = dto.getCode();
logger.info("code :"+code);
ResponseData data = channelFactory.getChannel(code).sendMsg(code);
System.out.println("test applicationcontextaware :"+ JSON.toJSON(data));
return data;
} }

玩转ApplicationContextAware的更多相关文章

  1. 玩转spring boot——快速开始

    开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...

  2. [C#] 软硬结合第二篇——酷我音乐盒的逆天玩法

    1.灵感来源: LZ是纯宅男,一天从早上8:00起一直要呆在电脑旁到晚上12:00左右吧~平时也没人来闲聊几句,刷空间暑假也没啥动态,听音乐吧...~有些确实不好听,于是就不得不打断手头的工作去点击下 ...

  3. [C#] 了解过入口函数 Main() 吗?带你用批处理玩转 Main 函数

    了解过入口函数 Main() 吗?带你用批处理玩转 Main 函数 目录 简介 特点 方法的参数 方法的返回值 与批处理交互的一个示例 简介 我们知道,新建一个控制台应用程序的时候,IDE 会同时创建 ...

  4. 玩转spring boot——开篇

    很久没写博客了,而这一转眼就是7年.这段时间并不是我没学习东西,而是园友们的技术提高的非常快,这反而让我不知道该写些什么.我做程序已经有十几年之久了,可以说是彻彻底底的“程序老炮”,至于技术怎么样?我 ...

  5. 玩转spring boot——结合redis

    一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...

  6. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  7. 玩转spring boot——结合JPA入门

    参考官方例子:https://spring.io/guides/gs/accessing-data-jpa/ 接着上篇内容 一.小试牛刀 创建maven项目后,修改pom.xml文件 <proj ...

  8. 玩转spring boot——结合JPA事务

    接着上篇 一.准备工作 修改pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

  9. 玩转spring boot——结合AngularJs和JDBC

    参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...

随机推荐

  1. Kera高层API

    目录 Keras != tf.keras Outline1 Metrics Step1.Build a meter Step2.Update data Step3.Get Average data C ...

  2. Sublime Text 报“Pylinter could not automatically determined the path to lint.py

    Pylinter could not automatically determined the path to lint.py. please provide one in the settings ...

  3. E - Multiplication Puzzle

    #include <iostream> #include <algorithm> #include <cstring> #include <cstdio> ...

  4. JavaScript 原生提供两个 Base64 相关的方法

    JavaScript 原生提供两个 Base64 相关的方法. btoa():任意值转为 Base64 编码 atob():Base64 编码转为原来的值 var string = 'Hello Wo ...

  5. .Net Core应用框架Util介绍(二) 转

    Util的开源地址 https://github.com/dotnetcore/util Util的开源协议 Util以MIT协议开源,这是目前最宽松的开源协议,你不仅可以用于商业项目,还能把Util ...

  6. STP-1-802.1D生成树协议及改进

    第一个 IEEE 标准化的STP也常称为“ 传统”STP,最初在802. 1D中进行了描述. 之后得到了改进,发布在所谓的修正案中:快速 STP( RSTP),在修正案802. 1w 中描述了它的标准 ...

  7. DP Training(Updating)♪(^∇^*)

    DP Training DP Training 01 https://vjudge.net/contest/220286 密码 nfls A 数塔(Easy) \(f[i][j]\) 表示当前选第 \ ...

  8. JDBC事务之例子篇

    上一篇随笔记了一些有关JDBC事务管理的理论知识.这篇来看例子(主要怕一篇随笔装所有东西太长了然后分开呵呵) 一般讲事务管理的,都是拿转钱来当例子的,嗯没错我们这也是. 这个是数据库中的t_accou ...

  9. STM32F4之SWO

    https://stm32f4-discovery.net/2014/12/library-46-debug-stm32f4-device-swo-feature/

  10. C++ Sort类成员的传递

    C++模板中提供了sort方法,一般有两种方法:传递函数,传递一个对象. 第一种方法:函数 bool compare(const string &strLeft, const string & ...