在某些特殊的情况下,Bean需要实现某个功能,但该功能必须借助于Spring容器才能实现,此时就必须让该Bean先获取Spring容器,然后借助于Spring容器实现该功能。为了让Bean获取它所在的Spring容器,可以让该Bean实现ApplicationContextAware接口。ApplicationContextAware 通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法。在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。看到—Aware就知道是干什么的了,就是属性注入的,但是这个ApplicationContextAware的不同地方在于,实现了这个接口的bean,当spring容器初始化的时候,会自动的将ApplicationContext注入进来。

1. 添加实现ApplicationContextAware的工具类

package learn.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; /**
* @author toutou
* @date by 2020/12
* @des
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext; @Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
} public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//获取Bean
public static <T> T getBean(Class<T> requiredType){
return getApplicationContext().getBean(requiredType);
}
public static <T> T getBean(String name){
return (T) getApplicationContext().getBean(name);
}
}

2. 接口中直接调用

    @GetMapping("home")
public Result getUser(){
UserAccountService userAccountService = SpringContextUtil.getBean(UserAccountService.class);
return Result.setSuccessResult(userAccountService.getUserAccountById(1));
}

3. service中内部调用

由于项目中配置了多个数据源,若所有mybatis mapper访问都集中在单个service方法中,@AutoDBDecision声明的数据源会串。所以需要颗粒化。这样就会在单个service中需要请求内部的方法,这时候也可以用上ApplicationContextAware工具类。

3.1 service中声明内部专用调用方法inside()

/**
* @author toutou
* @date by 2020/12
* des https://www.cnblogs.com/toutou/
*/
public interface UserAccountService {
default UserAccountService inside() {
return SpringContextUtil.getBean(UserAccountService.class);
} UserAccountVO getUserAccountById(Integer id); UserAccountVO getUserAccountById2(Integer id);
}

3.2 impl中调用方法

/**
* @author toutou
* @date by 2020/12
* des https://www.cnblogs.com/toutou/
*/
@Service
public class UserAccountServiceImpl implements UserAccountService{
@Autowired
UserAccountMapper userMapper; public UserAccountVO getUserAccountById(Integer id){
UserAccountVO accountVO = null;
UserAccount account = userMapper.selectByPrimaryKey(id);
if (account != null) {
accountVO = new UserAccountVO();
accountVO.setId(account.getId());
accountVO.setAccount(account.getAccount());
accountVO.setAge(account.getAge());
accountVO.setEmail(account.getEmail());
accountVO.setUsername(account.getUsername());
accountVO.setPhone(account.getPhone());
} return accountVO;
} public UserAccountVO getUserAccountById2(Integer id){
return inside().getUserAccountById(id);
}
}

其他参考/学习资料:

v源码地址

https://github.com/toutouge/javademosecond/tree/master/hellolearn

作  者:请叫我头头哥


出  处:http://www.cnblogs.com/toutou/


关于作者:专注于基础平台的项目开发。如有问题或建议,请多多赐教!


版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。


特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信


声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是作者坚持原创和持续写作的最大动力!

#comment_body_3242240 { display: none }

SpringBoot进阶教程(六十九)ApplicationContextAware的更多相关文章

  1. SpringBoot进阶教程(六十四)注解大全

    在Spring1.x时代,还没出现注解,需要大量xml配置文件并在内部编写大量bean标签.Java5推出新特性annotation,为spring的更新奠定了基础.从Spring 2.X开始spri ...

  2. SpringBoot进阶教程(六十五)自定义注解

    在上一篇文章<SpringBoot进阶教程(六十四)注解大全>中介绍了springboot的常用注解,springboot提供的注解非常的多,这些注解简化了我们的很多操作.今天主要介绍介绍 ...

  3. SpringBoot进阶教程(二十九)整合Redis 发布订阅

    SUBSCRIBE, UNSUBSCRIBE 和 PUBLISH 实现了 发布/订阅消息范例,发送者 (publishers) 不用编程就可以向特定的接受者发送消息 (subscribers). Ra ...

  4. SpringBoot进阶教程(五十九)整合Codis

    上一篇博文<详解Codis安装与部署>中,详细介绍了codis的安装与部署,这篇文章主要介绍介绍springboot整合codis.如果之前看过<SpringBoot进阶教程(五十二 ...

  5. SpringBoot进阶教程(六十八)Sentinel实现限流降级

    前面两篇文章nginx限流配置和SpringBoot进阶教程(六十七)RateLimiter限流,我们介绍了如何使用nginx和RateLimiter限流,这篇文章介绍另外一种限流方式---Senti ...

  6. SpringBoot进阶教程(六十)intellij idea project下建多个module搭建架构(上)

    在 IntelliJ IDEA 中,没有类似于 Eclipse 工作空间(Workspace)的概念,而是提出了Project和Module这两个概念.多module有一个父maven工程,多个子工程 ...

  7. SpringBoot进阶教程(六十二)整合Kafka

    在上一篇文章<Linux安装Kafka>中,已经介绍了如何在Linux安装Kafka,以及Kafka的启动/关闭和创建发话题并产生消息和消费消息.这篇文章就介绍介绍SpringBoot整合 ...

  8. SpringBoot进阶教程(六十一)intellij idea project下建多个module搭建架构(下)

    在上一篇文章<SpringBoot进阶教程(六十)intellij idea project下建多个module(上)>中,我们已经介绍了在intellij idea中创建project之 ...

  9. SpringBoot进阶教程(七十四)整合ELK

    在上一篇文章<SpringBoot进阶教程(七十三)整合elasticsearch >,已经详细介绍了关于elasticsearch的安装与使用,现在主要来看看关于ELK的定义.安装及使用 ...

随机推荐

  1. 课堂笔记【java JDBC】

    目录 JDBC简介 工作原理: 工作过程: JDBC驱动与连接 JDBC驱动 连接JDBC驱动 1.下载特定数据库的JDBCjar包 2.加载并注册数据库驱动 3.连接驱动 JDBC常见API JDB ...

  2. 第7.9节 案例详解:Python类封装

    上节介绍了Python中类的封装机制,本节结合一个具体例子进行详细说明. 我们定义一个Person类,其内部有姓名.年龄和类型三个实例变量,并定义了相关的存取方法: class Person():   ...

  3. PyQt(Python+Qt)学习随笔:QListWidget的addItems增加多项的方法

    老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 QListWidget支持一次增加多个项,对应的方法就是addItems方法,对应语法如下: add ...

  4. 第14.15节 爬虫实战1:使用Python和selenium实现csdn博文点赞

    写在前面:本文仅供参考学习,请勿用作它途,禁止转载! 在开始学爬虫时,学习了csdn博客专家(id:明天依旧可好 | 柯尊柏)<实战项目二:实现CSDN自动点赞>的文章,文章介绍了通过Py ...

  5. PyQt(Python+Qt)学习随笔:模式窗口的windowModality属性与modal属性

    windowModality属性 windowModality属性只对窗口对象有效,保存的是哪些类型的窗口被模式窗口阻塞. 模式窗口防止其他窗口中的部件获取输入.此属性的值控制对应窗口可见时阻塞哪些类 ...

  6. 手把手教你爬取B站弹幕!

    效果 输入要爬取的视频的BV号即可爬取该视频的弹幕. 过程 基本思路 基本的思路很简单,还是老步骤: 1.构造爬取的url 2.解析返回的数据 3.使用json或Xpath或正则表达式提取数据 4.保 ...

  7. PHP代码审计分段讲解(2)

    03 多重加密 源代码为: <?php include 'common.php'; $requset = array_merge($_GET, $_POST, $_SESSION, $_COOK ...

  8. linux 的bash 和 反斜杠

    export BERT_BASE_DIR=/path/to/bert/uncased_L-12_H-768_A-12 export GLUE_DIR=/path/to/glue python run_ ...

  9. Server returns invalid timezone. Go to 'Advanced' tab and set 'serverTimezone' property manually.

    用pycharm连接mysql报错 改变serverTimezone 改了之后确实可以连接上mysql数据库

  10. 查询满足条件的最新数据(逐步优化,mysql、达梦数据库)

    1.条件:报警信息表sensor_warning 2.需求: 查询当前车厢的.不同设备的.所有处理未完成的.不同报警原因的.时间最新的数据集合,最后按设备id或报警时间排序 3.原始sql,不满足实际 ...