[我正在从事Spring Boot项目。我在Spring Boot应用程序中创建一个singleton类。我想从我的singleton类的application.properties中获取属性。在非bean类中有可能吗?怎么办?
每个Spring bean是singleton scope by default。因此,您不应在Spring驱动的应用程序中使用Java单例类模式,而应使用spring bean并在其中注入@Value
。
非常感谢。我发现此解决方案可以使用ApplicationContextAware在非托管Bean类中注入Bean。
@Component
public class BeanInjecter implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}
//My non-bean class
public class NonBean{
Environment env = BeanInjecter.getBean(Environment.class);
String[] activeEnv = env.getActiveProfiles;
}