SpringBoot项目如何将Bean注入到普通类中

网友投稿 410 2022-09-15


SpringBoot项目如何将Bean注入到普通类中

目录如何将Bean注入到普通类中Spring管理的类获得一个注入的Bean方式非Spring管理的类获得一个注入的Bean方式普通类中通过ApplicationContext上下文获得Bean将ApplicationContext传入普通类中在普通类中如何获取Bean节点

如何将Bean注入到普通类中

Spring管理的类获得一个注入的Bean方式

@Autowired是一种注解,可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作,自动执行当前方法,如果方法有参数,会在IOC容器中自动寻找同类型参数为其传值。

如Controller中注入Bean可以这么写:

@RestController

public class TestController {

@Autowired

public TestBean bean;// 配置文件bean

}

非Spring管理的类获得一个注入的Bean方式

上述通过@Autowired注解注入的方式只可以用在Spring管理的类中,而普通类中通过这样的方式获得的Bean为null。

可以使用Spring上下文ApplicationContext获得Bean的方式,将Bean注入到普通类中

普通类中通过ApplicationContext上下文获得Bean

public class Test{

//声明要注入的Bean变量

private static TestBean bean;

// 通过applicationContext上下文获取Bean

public static void setApplicationContext(ApplicationContext applicationContext) {

bean = applicationContext.getBean(TestBean.class);

}

}

修改SpringBoot启动类

将ApplicationContext传入普通类中

@SpringBootApplication

public class TestrApplication {

public static void main(String[] args) {

final ApplicationContext applicationContext = SpringApplication.run(TestApplication.class, args);

// 将上下文传入Test类中,用于检测tcp连接是否正常

Test.setApplicationContext(applicationContext);

}

}

这样一个Spring的Bean就可以注入到普通类中使用了.

在普通类中如何获取Bean节点

/*

* 文件名:SpringContextUtil.java

* 描述:获取bean实例工具类

* 修改人:Wang Chinda

* 修改时间:2018/10/30

* 修改内容:新增

*/

package com.chinda.utils;

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import org.springframework.stereotype.Component;

/**

* 获取bean实例工具类

* @author Wang Chinda

* @date 2018/10/30

* @see

* @since 1.0

*/

@Component

public class SpringContextUtil 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;

}

/**

* 通过name获取Bean.

*

* @param name

* @return

*/

vgAwNNpublic static Object getBean(String name) {

return getApplicationContext().getBean(name);

}

/**

* 通过class获取Bean.

*

* @param clazz

* @param

* @return

*/

public static T getBean(Class clazz) {

return getApplicationContext().getBean(clazz);

}

/**

* 通过name以及Class返回指定的Bean

*

* @param name

* @param clazz

* @param

* @return

*/

public static T getBean(String name, Class clazz) {

return getApplicationContext().getBean(name, clazz);

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:IT运维管理和传统的网络管理的区别(it运维的主要技术有哪些)
下一篇:网络工程师级考试大纲(网络工程师中级职称考试内容)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~