在春季启动时在非bean类中使用@value

问题描述 投票:0回答:2

[我正在从事Spring Boot项目。我在Spring Boot应用程序中创建一个singleton类。我想从我的singleton类的application.properties中获取属性。在非bean类中有可能吗?怎么办?

java spring spring-boot singleton spring-ioc
2个回答
1
投票

每个Spring bean是singleton scope by default。因此,您不应在Spring驱动的应用程序中使用Java单例类模式,而应使用spring bean并在其中注入@Value


0
投票

非常感谢。我发现此解决方案可以使用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;

}
© www.soinside.com 2019 - 2024. All rights reserved.