我有一个Configuration.class,它从application.properties
获取属性。
@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吗?
否和是。
不,因为这就是Spring和依赖项注入的全部思想。您必须使用能够访问SpringApplicationContext的东西。
是的,因为您可以使用发布-订阅模式,或者您可以使一些上下文感知bean成为单例,并让它们公开所有必要的属性。但这只是对有权访问Spring上下文的对象的委派。打个比方:这不是犯罪,它只是出售武器并把钱给一个真正开枪的人:)