前言
按照Spring的默认规则,只有受Spring容器管理的类(添加了@Component、@Service等注解的类),才能获取Spring中的容器中的Bean(目标类的全局单实例)
但在某些场景下,我们希望只是在某些业务类中的对象中暂时获取Spring中的容器中的Bean,当完成业务后,垃圾回收器会自动回收到该对象,毕竟业务类的对象只是暂时使用,没有让它一直存在的必要。
解决方案
使用hutool工具类来获取想要的Bean
引入hutool extra工具包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-extra</artifactId>
<version>5.8.16</version>
</dependency>
添加@EnableSpringUtil注解
为了开启全局允许,我在Application上面直接添加了该注解
@SpringBootApplication
@EnableSpringUtil
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
getBean方法
hutool extra提供了以下几个方法来获取bean,可以根据需要传入bean的名称、bean的类型等信息,根据自己的需要来选择即可。
public static <T> T getBean(String name) {
return getBeanFactory().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getBeanFactory().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getBeanFactory().getBean(name, clazz);
}
public static <T> T getBean(TypeReference<T> reference) {
ParameterizedType parameterizedType = (ParameterizedType)reference.getType();
Class<T> rawType = (Class)parameterizedType.getRawType();
Class<?>[] genericTypes = (Class[])Arrays.stream(parameterizedType.getActualTypeArguments()).map((type) -> {
return (Class)type;
}).toArray((x$0) -> {
return new Class[x$0];
});
String[] beanNames = getBeanFactory().getBeanNamesForType(ResolvableType.forClassWithGenerics(rawType, genericTypes));
return getBean(beanNames[0], rawType);
}
举个例子
以下代码用于获取一个已经存在的Bean
MulticastSendingMessageHandler multicastHandler = SpringUtil.getBean("multicastHandler");
getProperty方法
除了获取Bean,有时候我们还想直接获取配置文件里面定义的变量值,则可以用getProperty方法来获取,其方法原型如下。
public static String getProperty(String key) {
return null == applicationContext ? null : applicationContext.getEnvironment().getProperty(key);
}
举个例子
以下代码用于获取配置文件中指定的端口号
Integer port = Integer.valueOf(SpringUtil.getProperty("custom..port"));