在非spring管理的包中引入spring管理的类, 可以使用一个类继承ApplicationContextAware即可

分两种, 第一种该类在spring的包扫描范围之下:

package com.iwhere.test.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; /**
* 在普通类中引入spring中的bean, 在springboot的扫描包下
* @ServletComponentScan
*
* 如果不在springboot的包扫描下, 则不需要component, 但需要在App.java中引入
* @Import(value={SpringAppUtils.class})
*
* @author 231
* @time 2017年3月15日 下午2:40:32 2017
*/
@Component
public class SpringAppUtils implements ApplicationContextAware {
private static Logger LOGGER = LoggerFactory.getLogger(SpringAppUtils.class);
private static ApplicationContext applicationContext; @Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
if (SpringAppUtils.applicationContext == null) {
applicationContext = context;
}
LOGGER.info("springAppUtils is init");
} /**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
} /**
* 通过那么获取bean
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
} /**
* 通过class获取bean
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
} /**
* 通过name和class获取bean
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}

第二种: 配置类不在springboot扫描之下:

此时类上不需要加 @Component 注解

但需要在App.java中引入

@Import(value={SpringAppUtils.class})

@SpringBootApplication
@ServletComponentScan
@Import(value={SpringUtil.class})
publicclass App { {main} }

之后有一次在监听器中使用到, 感觉这两种方法都不太好用, 于是有了第三种:

mongoTemplate = WebApplicationContextUtils.getWebApplicationContext(servlet).getBean(MongoTemplate.class);

这个可以直接获取到springboot的工厂, 然后使用工厂的方法获取bean对象, 需要传入一个servlet对象, 可在controller或者listener中使用

4, 获取spring的上下文:

package com.iwhere.demo.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; /**
* 获取spring上下文
* @author wenbronk
* @time 2017年4月18日 下午12:49:59 2017
*/
@Component
public class SpringContext implements ApplicationContextAware {
private static Logger LOGGER = LoggerFactory.getLogger(SpringContext.class);
private static ApplicationContext applicationContext; @Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
if (applicationContext == null) {
applicationContext = arg0;
}
LOGGER.info("spring application context is init");
} /**
* 获取applicationContext
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
} /**
* 通过name获取bean
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
} /**
* 通过class获取bean
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
} /**
* 通过name和class获取bean
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
} }

原文地址: http://412887952-qq-com.iteye.com/blog/2292388

springboot-9-在springboot中引入bean的更多相关文章

  1. SpringBoot中的bean加载顺序

    https://www.dazhuanlan.com/2019/10/22/5daebc5d16429/ 最近在做传统Spring项目到SpringBoot项目迁移过程中,遇到了一些bean加载顺序的 ...

  2. SSM项目 以及 springboot 中引入swagger2的方法

    swagger2是一个非常好用的接口文档,在开发的过程中方便前后端接口的交接. 下面我们就来讲讲在使用java时,分别在SSM框架,以及springboot+mybatis框架中引入swagger2的 ...

  3. SpringBoot 之 普通类获取Spring容器中的bean

    [十]SpringBoot 之 普通类获取Spring容器中的bean   我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器 ...

  4. 为什么在SpringBoot+maven的项目中,所引入的依赖包可以不指定依赖的版本号?

    当在Springboot项目中引入了spring-boot-starter-parent,则可以不用引入依赖包版本号,比如: <parent> <groupId>org.spr ...

  5. SpringBoot下使用AspectJ(CTW)下不能注入SpringIOC容器中的Bean

    SpringBoot下使用AspectJ(CTW)下不能注入SpringIOC容器中的Bean 在SpringBoot中开发AspectJ时,使用CTW的方式来织入代码,由于采用这种形式,切面Bean ...

  6. SpringBoot学习(七)-->SpringBoot在web开发中的配置

    SpringBoot在web开发中的配置 Web开发的自动配置类:在Maven Dependencies-->spring-boot-1.5.2.RELEASE.jar-->org.spr ...

  7. springboot+redis+虚拟机 springboot连接linux虚拟机中的redis服务

    文章目录 1.前提条件:确保虚拟机开启.并且连接到redis 2.新建立一个springboot项目,创建项目时勾选web选项 3.在pom中引入redis依赖 4.在application.prop ...

  8. 尚硅谷springboot学习10-@PropertySource,@ImportResource,@Bean

    @PropertySource 使用指定的属性文件而不一定是application.xxx 同样可以注入相关内容 @ImportResource 导入Spring的配置文件,让配置文件里面的内容生效: ...

  9. SpringBoot配置——@PropertySource、@ImportResource、@Bean

    @PropertySource:加载指定的配置文件 package com.hoje.springboot.bean; import org.springframework.beans.factory ...

随机推荐

  1. ReportMachine OCX

    http://rmachine.haotui.com/thread-55-1-1.html 偏高偏低提示 [IF( [RMDBDataSet1."abnormalIndicator" ...

  2. 阉割版BBBlack安装Debian

    开门见山,直入主题 咸鱼入手3块阉割ARM板,经过快递近6天运输到手,不过价格便宜 东西下面这样的(借了咸鱼的图): 发现这块板是阉割版的国外beagleboard.org型号为BeagleBone ...

  3. 我也谈谈.NET程序员工资低

    我从2011年下半年预谋转型,2012春季正式转型到iOS,看了<经过本人 6 年.net 工作经验证明 .net 工资确实比 Java 低>这篇文章,一下子有很多感慨. 我不好意思算我干 ...

  4. 关于Java连接SQL Sever数据库

    1.前提条件 需要: 1>本机上装有SQL Sever数据库(2005.2008或者更高版本) 2>eclipse或者myeclipse开发环境 3>jar文件(名为sql_jdbc ...

  5. navigationController背景图,文字,事件定义

    //设置背景图片 [self.navigationController.navigationBar setBackgroundImage:imag forBarMetrics:UIBarMetrics ...

  6. [翻译]ASP.NET Web API 2 中的全局错误处理

    目录 已存在的选项 解决方案预览 设计原则 什么时候去用 方案详情 示例 附录: 基类详情 原文链接 Global Error Handling in ASP.NET Web API 2 由于翻译水平 ...

  7. 委托发展史(Linq操作符)

    嗯~这篇就讲讲Linq吧! 之前讲过Lambda最后进化到了令人发指的地步: Func<string, int> returnLength; returnLength = text =&g ...

  8. Validation failed for one or more entities. See ‘EntityValidationErrors’ property for moredetails[转]

    这里给大家介绍一个Exception类,让我们能够轻松的知道具体的哪一个字段出了什么问题. 那就是 System.Data.Entity.Validation.DbEntityValidationEx ...

  9. 枚举类型内部函数 enumerate

    enumerate()说明enumerate()是python的内置函数enumerate在字典上是枚举.列举的意思对于一个可迭代的(iterable)/可遍历的对象(如列表.字符串),enumera ...

  10. Redis安装步骤 - linux系统下

    https://blog.csdn.net/lzj3462144/article/details/70973368 https://www.cnblogs.com/pyyu/p/9467279.htm ...