Why is Spring @Value incompatible with @Controller?

前端 未结 4 1966
执念已碎
执念已碎 2021-01-13 13:00

I\'m looking for a better understanding of this problem. A workaround is pretty simple, namely move the configuration data to another class that does not have proxies/advic

4条回答
  •  梦毁少年i
    2021-01-13 13:50

    I had the same problem and it was the fact that I needed BOTH

    To get these two senarios to work

    1. inject an attribute (via @Value) into a Controller
    2. Inject a managed bean (via @Inject) that hasan attribute (via @Value) into the Controller

    I hope this helps.

    Here is the web.xml.

        
        spring
        
            org.springframework.web.servlet.DispatcherServlet
        
        
            contextConfigLocation
            classpath:/spring-config/spring-servlet.xml
        
        1
    
    
    
        spring
        /
    
    

    Here is spring-servlet.xml: The key was to have BOTH util:properties and context:property-placeholder. Although they locate the same file, they serve different purposes.

    
    
    
    
    
    
     
    

    Here is a snippet of my controller class:

    @Controller
    @RequestMapping("/fooController")
    public class MyController {
    
    @Value("${message1}")
    public String message1;
    
    @Inject
    public ConfigProperties configProperties;
    

    Lastly, here is my class that I inject the property into:

    @Service
    public class ConfigProperties {
    
    @Value("${message1}")
    public String message1;
    }
    

    That worked for me and will work for you. Good Luck!

提交回复
热议问题