简体   繁体   中英

In spring-boot, is it possible to get properties without being a spring bean?

I have a Configuration.class, which fetches properties from application.properties .

@Component
public class Configuration {

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

I have another class called Fetcher , which needs the property.

class Fetcher {

    @Autowired
    private Configuration configuration;

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

Of course the above code would fail because Fetcher is not a Spring Bean(I didn't add @Component / @Service / @Repository to it). My question is, is it possible to get someValue in Fetcher without making it a Spring Bean?

No and yes.

No is because that's the whole idea of Spring and dependency injection. You have to use something which will have access to Spring ApplicationContext.

Yes, because you may use publish–subscribe pattern, or you may make some of your context aware beans to be a singleton, and let them expose all the necessary properties. But it is just delegation to object which has access to Spring context. To make an analogy: it is not the crime, it is just selling weapon and giving money to someone who will make an actual shot :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM