在不受Spring管理的类中注入spring 管理的对象

本文介绍了如何在不受Spring管理的普通Java类中使用Spring Data JPA的Repository接口和读取properties文件属性。通过获取Spring的ApplicationContext对象来间接注入Spring管理的对象,提供了包括加载配置文件、Spring工具类、继承抽象类、实现接口等多种方法来获取ApplicationContext,并展示了通过beanId或beanClass获取bean的示例。

前几天在做一个任务时,需要在一个普通的java类(不受Spring管理的类)中,调用 spring data jpa的某个xxxReponsitory 接口,同时需要读取properties 文件中的属性值,试了很多方法拿到的都是null,花了半个下午的时间才搞定,现在记录下解决方法。

这个问题网上大概有两个思路:

1. 将这个不受Spring管理的类交给Spring管理,然后就可以依赖注入 spring管理的对象了;
这个思路的方法对我的遇到的问题没有作用,在这里就不多说了,因为我这个类被调用的时候是new出来的。

**New出来的对象是不受spring管理的。**

2. 获取spring 的上下文对象,从而拿到spring管理的对象。
这里分为两个步骤 :
步骤一:获取 spring ApplicationsContext对象,以下几种方法都可行:
(1) 通过加载配置文件获取ApplicationContext对象
Spring中的几种容器都支持加载xml配置文件:

ApplicationContext context = new GenericXmlApplicationContext
("applicationContext.xml");
ApplicationContext context = new FileSystemXmlApplicationContext
("applicationContext.xml");
ApplicationContext context = new ClassPathXmlApplicationContext
("applicationContext.xml");

以上三个任选一个都可以。

(2)通过Spring提供的工具类获取ApplicationContext对象

2 ApplicationContext context1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
3 ApplicationContext context2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);

这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,
上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。

(3)通过继承抽象类ApplicationObjectSupport来获取act对象

抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。
Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

(4)通过继承抽象类WebApplicationObjectSuport来获取act对象

类似上面方法,调用getWebApplicationContext()获取WebApplicationContext

(5)实现接口ApplicationContextAwarc来获取act对象

实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。
Spring初始化时,会通过该方法将ApplicationContext对象注入。

(6)通过Spring提供的ContextLoader来获取act对象

WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); 

步骤二:通过ApplicationContext对象 获取spring管理的对象

Xxxx xxxx = (Xxxx)context.getBean(“beanId”);
或者
Xxxx xxxx = (Xxxx)context.getBean(beanClass);
如果通过beanId获取bean,beanId需要是配置文件中指定好了的
如果通过beanClass获取bean,则该bean需要在spring的扫描范围内

例:
1)通过beanId 获取配置文件中的属性
在这里插入图片描述

  Properties props = (Properties) context.getBean("testProperties");
  enterpriseName = props.getProperty("default.enterprise.name");

2)通过beanClass获取UserRepository

UserRepository userRepository = context.getBean(UserRepository.class);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值