dynamically change spring beans

前端 未结 5 1964
我在风中等你
我在风中等你 2021-01-01 01:24

how do I dynamically change the properties of a bean at runtime using java spring? I have a bean mainView, which should use as property \"class\" either \"class1\" or \"clas

5条回答
  •  心在旅途
    2021-01-01 01:49

    You want the PropertyPlaceholderConfigurer. That section of the manual demonstrates it better than I could on the spot.

    In your example, you'd need to either to change the value of the property to class1 or class2 (the name of the desired bean in the spring context).

    Alternately, your configuration could be:

    
        
        
            
                
            
        
    
    

    with the configuration file containing: classToUse=fully.qualified.name.of.some.Class

    Using bean or class names would not be acceptable in a user-editable configuration file, and you really need to use "Y" and "N" as the configuration parameter values. In that case, you'll just have to do this in Java, Spring isn't meant to be turing-complete.

    mainView could access the application context directly:

    if (this.withSmartCards) {
        this.class_ = context.getBean("class1");
    } else {
        this.class_ = context.getBean("class2");
    }
    

    A cleaner solution would be encapsulating processing of the user configuration in its own class that would do the above to reduce the number of classes that need to be ApplicationContextAware and inject it into your other classes as needed.

    Using BeanFactoryPostProcessor, you could register a definition of the class property programmatically. Using FactoryBean, you can create a bean dynamically. Both are somewhat advanced usages of Spring.

    An aside: I'm not sure if your example config is legal, given the cyclic dependency between mainView and class1 / class2.

提交回复
热议问题