Injecting Properties using Spring & annotation @Value

后端 未结 2 463
小鲜肉
小鲜肉 2020-12-15 09:29

I am trying to load a properties file into a Spring bean and then inject that bean into a class.

The only part I can\'t get to work seems to be using the @Resourc

2条回答
  •  再見小時候
    2020-12-15 09:44

    For your solution to work you would also need to make foo a Spring managed bean; because otherwise how would Spring know that it has to deal with any of your annotations on your class?

    • You can either specify it in your appcontext xml as a bean with ..class="foo"
    • Or use component-scan and specify a base package which contains your foo class.

    Since I'm not entirely sure this is exactly what you want (don't you want a .properties file to be parsed by Spring and have it's key-value pairs available instead of a Properties object?), I'm suggesting you another solution: Using the util namespace

    
    

    And reference the values inside your beans (also, have to be Spring managed):

    @Value("#{props.foo}")
    public void setFoo(String foo) {
        this.foo = foo;
    }
    

    EDIT:

    just realized that you are importing org.springframework.context.ApplicationContext in your class which is probably unnecessary. I strongly encourage you to read Spring reference at least the first few chapters, because a) it's a great read b) you will find it much easier to understand Spring if the basics are clear.

提交回复
热议问题