Spring Boot普通类调用bean
1 在Spring Boot可以扫描的包下
假设我们编写的工具类为SpringUtil。
如果我们编写的SpringUtil在Spring Boot可以扫描的包下或者使用@ComponentScan引入自定义的包了,那么原理很简单,只需要使得SpringUtil实现接口:ApplicationContextAware,然后加上@Component 注解即可,具体编码如下:
com.kfit.base.util.SpringUtil:
package com.kfit.base.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 普通类调用Spring bean对象:
* 说明:
* 1、此类需要放到App.java同包或者子包下才能被扫描,否则失效。
* @author Administrator
*/
@Component
publicclass SpringUtil implements ApplicationContextAware{
privatestatic ApplicationContext applicationContext = null;
@Override
publicvoid setApplicationContext(ApplicationContext applicationContext) throwsBeansException
{
if(SpringUtil.applicationContext == null){
SpringUtil.applicationContext = applicationContext;
}
System.out.println("---------------------------------------------------------------------");
System.out.println("---------------------------------------------------------------------");
System.out.println("---------------com.kfit.base.util.SpringUtil------------------------------------------------------");
System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+SpringUtil.applicationContext+"========");
System.out.println("---------------------------------------------------------------------");
}
//获取applicationContext
publicstatic ApplicationContext getApplicationContext() {
returnapplicationContext;
}
//通过name获取 Bean.
publicstatic Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
publicstatic <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
publicstatic <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
启动应用,查看控制台的打印信息是否有:
======ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,
2 不在Spring Boot的扫描包下方式一
这种情况处理起来也很简单,先编写SpringUtil类,同样需要实现接口:ApplicationContextAware,具体编码如下:
simple.plugin.spring.SpringUtil
package simple.plugin.spring;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
publicclass SpringUtil implements ApplicationContextAware{
privatestatic ApplicationContext applicationContext = null;
@Override
publicvoid setApplicationContext(ApplicationContext applicationContext) throwsBeansException
{
if(SpringUtil.applicationContext == null){
SpringUtil.applicationContext = applicationContext;
}
System.out.println("---------------------------------------------------------------------");
System.out.println("---------------------------------------------------------------------");
System.out.println("---------------simple.plugin.spring.SpringUtil------------------------------------------------------");
System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+SpringUtil.applicationContext+"========");
System.out.println("---------------------------------------------------------------------");
}
//获取applicationContext
publicstatic ApplicationContext getApplicationContext() {
returnapplicationContext;
}
//通过name获取 Bean.
publicstatic Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
publicstatic <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
publicstatic <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
之后这一步才是关键,使用@Bean注解,在App.java类中将SpringUtil注解进来,代码如下:
package com.kfit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import simple.plugin.spring.SpringUtil;
/**
* Hello world!
*
*/
//其中@SpringBootApplication申明让spring boot自动给程序进行必要的配置,等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan
@SpringBootApplication
@ServletComponentScan
public class App {
/**注册Spring Util
* 这里为了和上一个冲突,所以方面名为:springUtil2
* 实际中使用springUtil
*/
@Bean
public SpringUtil springUtil2(){return new SpringUtil();}
/**
*
参数里VM参数设置为:
-javaagent:.\lib\springloaded-1.2.4.RELEASE.jar -noverify
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
3 不在Spring Boot的扫描包下方式二
代码基本和上面都是相同的,主要是在App.java中使用@Import进行导入。
而且在SpringUtil是不需要添加@Component注解
@SpringBootApplication
@ServletComponentScan
@Import(value={SpringUtil.class})
publicclass App {
//省略其它代码.
}
说明以上3中方式都生效了,这3中方式根据实际情况选择一种方式就可以了。
那么这样子在普通类既可以使用:
SpringUtil.getBean() 获取到Spring IOC容器中的bean。
当然也可以在Spring管理的类中使用:
@Resouce或者@Autowired 进行注入使用,当然我们这个类的核心是普通类可以调用spring的bean进行使用了,是不是很神奇呢。
Spring Boot普通类调用bean的更多相关文章
- 17、Spring Boot普通类调用bean【从零开始学Spring Boot】
转载:http://blog.csdn.net/linxingliang/article/details/52013017 我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个 ...
- (17)Spring Boot普通类调用bean【从零开始学Spring Boot】
我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器进行管理,但是在实际当中,我们往往会碰到在一个普通的Java类中,想直接使用 ...
- Spring Boot动态注入删除bean
Spring Boot动态注入删除bean 概述 因为如果采用配置文件或者注解,我们要加入对象的话,还要重启服务,如果我们想要避免这一情况就得采用动态处理bean,包括:动态注入,动态删除. 动态注入 ...
- spring boot 启动类一定要放置到包的根目录下,也就是和所有包含java文件的包在同一级目录。如果不放置在根目录下,将会提示 no mybatis mapper was found
spring boot 启动类一定要放置到包的根目录下,也就是和所有包含java文件的包在同一级目录.将会将同一目录下的包扫描成bean. 如果不放置在根目录下,将会提示 no mybatis map ...
- Spring Boot 异步方法的调用
Spring Boot 异步方法的调用 参考资料: 1.Spring Boot中使用@Async实现异步调用 使用方法 两个步骤: 1.开启配置 @EnableAsync,这一步特别容易忘记,导致测试 ...
- Spring Cloud Ribbon负载均衡配置类放在Spring boot主类同级增加Exclude过滤后报Field config in com.cloud.web.controller.RibbonConfiguration required a bean of type 'com.netflix.client.config.IClientConfig' that could not b
环境: Spring Cloud:Finchley.M8 Spring Boot:2.0.0.RELEASE 目录结构: 可以看到代码第13行的注释,我已经在@ComponentScan注解中添加了E ...
- Spring Boot发布和调用RESTful web service
Spring Boot可以非常简单的发布和调用RESTful web service,下面参考官方指导体验一下 1.首先访问 http://start.spring.io/ 生成Spring Boot ...
- spring boot测试类自动注入service或dao
使用Spring Boot进行单元测试时,发现使用@Autowired注解的类无法自动注入,当使用这个类的实例的时候,报出NullPointerException,即空指针异常. Spring Boo ...
- Spring Boot 使用 JAX-WS 调用 WebService 服务
除了 CXF 我们还可以使用 Spring Boot 自身默认的组件 JAX-WS 来实现 WebService 的调用. 本项目源码 github 下载 1 新建 Spring Boot Maven ...
随机推荐
- 2014.9.25DOM元素操作
2.操作样式class a.className=”block” class样式,代码赋值的方式 (五)找相关元素 a.nextSibling 下一层,下一个同辈元素 a.previousSibling ...
- 深度优先搜索——迷宫问题(华为oj)
题目描述: 定义一个二维数组N*M(其中2<=N<=10;2<=M<=10),如5 × 5数组下所示: int maze[5][5] = { 0, 1, 0, 0, 0, 0, ...
- leetcode String to Integer (atoi) python
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int "& ...
- Python3 关于UnicodeDecodeError/UnicodeEncodeError: ‘gbk’ codec can’t decode/encode bytes类似的文本编码问题
以下是小白的爬虫学习历程中遇到并解决的一些困难,希望写出来给后来人,如有疏漏恳请大牛指正,不胜感谢! 首先,我的代码是这样的 import requests url = 'http://www.acf ...
- vs 2013下自定义ASP.net MVC 5/Web API 2 模板(T4 视图模板/控制器模板)
vs 2013下自定义ASP.net MVC 5/Web API 2 模板(T4 视图模板/控制器模板): Customizing ASP.NET MVC 5/Web API 2 Scaffoldi ...
- start stack
Start OpenStack Services After launching your stack by Devstack, you maybe stop some services or reb ...
- vb6.0 倒计时
Dim t Dim start As Boolean Private Sub Command1_Click() If start = False Then t = Val(Text1) * 3600 ...
- MyEclipse13中修改Servlet.java源代码
Servlet.java源代码想要修改的步骤,与低版本的不同废话少说,直接来步骤: 1,在myEclipse的安装目录中搜索com.genuitec.eclipse.wizards文件,如图:选择co ...
- 基于Proxy思想的Android插件框架
意义 研究插件框架的意义在于下面几点: 减小安装包的体积,通过网络选择性地进行插件下发 模块化升级.减小网络流量 静默升级,用户无感知情况下进行升级 解决低版本号机型方法数超限导致无法安装的问题 代码 ...
- PID教程
PID教程 介绍 本教程将向您展示了比例每一个比例项 (P)的特点,积分项(I)和微分项 (D) 控制,以及怎样使用它们来获得所需的响应.在本教程中,我们会考虑下面单位反馈系统: Plant[被控对象 ...