How to inject a value to bean constructor using annotations

前端 未结 2 1497
夕颜
夕颜 2020-12-03 02:46

My spring bean have a constructor with an unique mandatory argument, and I managed to initialize it with the xml configuration :



        
相关标签:
2条回答
  • 2020-12-03 03:15

    As Bozho said, instead of constructor arg you could set the property...@PostConstruct will only get called after all the properties are set...so, you will still have your string available ...

    0 讨论(0)
  • 2020-12-03 03:36

    First, you have to specify the constructor arg in your bean definition, and not in your injection points. Then, you can utilize spring's @Value annotation (spring 3.0)

    @Component
    public class DefaultInterfaceParameters {
    
        @Inject
        public DefaultInterfaceParameters(@Value("${some.property}") String value) {
             // assign to a field.
        }
    }
    

    This is also encouraged as Spring advises constructor injection over field injection.

    As far as I see the problem, this might not suit you, since you appear to define multiple beans of the same class, named differently. For that you cannot use annotations, you have to define these in XML.

    However I do not think it is such a good idea to have these different beans. You'd better use only the string values. But I cannot give more information, because I dont know your exact classes.

    0 讨论(0)
提交回复
热议问题