Spring annotation-driven SEVEN - use registration component FactoryBean

You can also use the factory provided by Spring bean to register a component in the actual development

First, create an implementation of the bean plant

/ ** 
 * T is the generic bean objects obtained by factory bean 
 * 
 * / 
public  class ColorFactory the implements the FactoryBean <Color> {
     / ** 
     * to load the container obtained by the method getObject factory bean bean 
     * / 
    public Color getObject ( ) throws Exception {
         return  new new Color (); 
    } 
    / ** 
     * returns the type of the bean container ioc 
     * / 
    public class <?> getObjectType () {
         // the TODO Auto-Generated Method Stub 
        return Color. class ; 
    } 
    / ** 
     * set bean objects inside the container whether singleton
     * Returns is true: the singleton 
     * returns flase: Example of Multi 
     * / 
    public  Boolean isSingleton () {
         return  to false ; 
    } 
}

The ColorFactory registered vessel through @Bean annotation category in the master configuration

@Configuration
 public  class MainConfig2 {
     // method called default ID 
    @Bean
     public ColorFactory getColorFactory () {
         return  new new ColorFactory (); 
    } 
}

We get bean object container by acquiring the container component id of the way in the test class

public class IOCTest {
    @Test
    public void test4() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
        Object colorFactory = applicationContext.getBean("getColorFactory") ;
        System.out.println(colorFactory);
    }
}

operation result:

com.wxj.bean.Color@57d5872c

We found present in the reservoir is not ColorFactory to like, but the Color object by observation shows that container method returns the object to be created by the factory bean getObject () and register the vessel.

So if you must get ColorFactory objects, how you should get it? Need to add a "&" symbol to get in front of the bean id name.

public class IOCTest {
    @Test
    public void test4() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
        Object colorFactory = applicationContext.getBean("&getColorFactory") ;//"&"可获得工厂bean对象
        System.out.println(colorFactory);
        
    }

}

operation result:

com.wxj.ColorFactory@57d5872c

Extended:

  When using a single instance, getObject method will only be called once, and in the case of multi-instance every acquisition bean calls the getObject () method.

Guess you like

Origin www.cnblogs.com/xingjia/p/11210826.html