在spring-boot中,是否有可能获得属性而不是Spring bean?

问题描述:

我有一个Configuration.class,它从application.properties获取属性。在spring-boot中,是否有可能获得属性而不是Spring bean?

@Component 
public class Configuration { 

    @Value("${someValue}") 
    public String someValue; 
} 

我有另一个类Fetcher,它需要属性。

class Fetcher { 

    @Autowired 
    private Configuration configuration; 

    public void doSomethingWithSomeValue() { 
     System.out.println(configuration.someValue); 
    } 
} 

当然上面的代码会失败,因为Fetcher不是一个Spring bean(我没加@Component/@Service/@Repository它)。我的问题是,是否有可能在Fetcher中获得someValue而不使其成为Spring Bean?

+0

也许,将配置文件读入地图并从那里获取? –

+0

看看https://*.com/a/18486178/1032167和https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html – varren

不,是的。

不是因为这是Spring和依赖注入的整个想法。你必须使用能够访问Spring ApplicationContext的东西。

是的,因为你可以使用发布 - 订阅模式,或者你可以让你的一些情境感知bean成为单例,并让它们公开所有必要的属性。但它只是代表访问Spring上下文的对象。打个比方:这不是犯罪,它只是出售武器,并给予实际开枪的人的钱:)