BeanFactory
2019-07-02 本文已影响0人
dwwl
一个项目中会经常遇到的场景:在一些未被spring管理的JAVA类中,是不能通过@AutoWired
和@Resource
注入对象的。这种情况下,一种比较简单的方法实现接口ApplicationContextAware
,ps : 目前项目中所使用的也是这种方式。
简单Demo
BeanFactory.java
package com.mpt.arguResolver;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* @author huangQiChang
* @date 2019/7/2
*/
public class BeanFactory implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanFactory.applicationContext = applicationContext;
}
public static <T> T getBean(String beanName) {
Object object = null;
try {
object = applicationContext.getBean(beanName);
} catch (NoSuchBeanDefinitionException var3) {
throw new RuntimeException(var3);
}
return (T) object;
}
public static <T> T getBean(Class<T> clazz) {
T object = null;
try {
object = applicationContext.getBean(clazz);
} catch (NoSuchBeanDefinitionException var3) {
}
return object;
}
}
ArguresolverApplication.java(引导类)
package com.mpt.arguResolver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class ArguresolverApplication {
public static void main(String[] args) {
SpringApplication.run(ArguresolverApplication.class, args);
}
@Bean
public BeanFactory beanFactory() {
return new BeanFactory();
}
}
MTest.java(未由spring管理的普通java类)
package com.mpt.arguResolver.test;
import com.mpt.arguResolver.BeanFactory;
import com.mpt.arguResolver.service.UserService;
/**
* @author huangQiChang
* @date 2019/7/2
*/
public class MTest {
private static UserService userService;
static {
userService = BeanFactory.getBean(UserService.class);
}
public String testMethod() {
String s = userService.service_test();
return s;
}
}
SpringBoot测试类:
package com.mpt.arguResolver;
import com.mpt.arguResolver.test.MTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ArguresolverApplicationTests {
@Test
public void test() {
MTest mTest = new MTest();
mTest.testMethod();
}
}
//可以正常获取UserServicce对象并执行其中的方法
注意实现ApplicationContextAware
接口的BeanFactory
这种类需要交由Spring容器管理,即被@Component
注解或是SpringBoot的Application中通过@Bean
的方式。