当一个类实现了这个接口之后,这个类就可以方便地获得 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. G - You Are the One(需要重想一遍)

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

  2. ajax中get和post区别

    参考地址:http://blog.csdn.net/laijieyao/article/details/40426257 首先要明确的事$.get方法是使用GET方式进行异步请求.$.post方法使用 ...

  3. hdu 5971 Wrestling Match 判断能否构成二分图

    http://acm.hdu.edu.cn/showproblem.php?pid=5971 Wrestling Match Time Limit: 2000/1000 MS (Java/Others ...

  4. C#私有的构造函数的作用

    C#私有的构造函数的作用:当类的构造函数是私有的时候,也已防止C1 c1=new C1();实例化类.常见的应用是工具类和单例模式. using System;using System.Collect ...

  5. SimpleDateFormat 如何安全的使用?

     前言 为什么会写这篇文章?因为这些天在看<阿里巴巴开发手册详尽版>,没看过的可以关注微信公众号:zhisheng,回复关键字:阿里巴巴开发手册详尽版 就可以获得. 关注我 转载请务必注明 ...

  6. 代码review

    对于代码review个人也有些小小的看法: 1.首先我觉得我们所有开发人员要弄明白 现在Code Review 的目的 ,凡事不弄明白目的,无法做好完成一件事情,个人觉得有以下一些目的: a)可以在项 ...

  7. MD5加密的方法

    #region MD5加密 /// <summary> /// MD5加密 /// </summary> /// <param name="strPwd&quo ...

  8. 2189 数字三角形W

    2189 数字三角形W 时间限制: 1 s 空间限制: 32000 KB 题目等级 : 黄金 Gold       题目描述 Description 数字三角形要求走到最后mod 100最大 输入描述 ...

  9. Android 视频录制 java.lang.RuntimeException: start failed.

    //mRecorder.setVideoSize(320, 280); // mRecorder.setVideoFrameRate(5); mRecorder.setOutputFile(viodF ...

  10. IOS中Llabel整理

    ·UILable是iPhone界面最基本的控件,主要用来显示文本信息.·常用属性和方法有:1.创建CGRect rect = CGRectMake(100, 200, 50, 50);UILabel ...