Spring 3 @Component and static factory method

牧云@^-^@ 提交于 2019-11-29 13:11:02

I am afraid you can't do this currently. However it is pretty simple with Java Configuration:

@Configuration
public class Conf {

    @Bean
    public MyObject myObject() {
        return MyStaticFactory.getObject()
    }

}

In this case MyStaticFactory does not require any Spring annotations. And of course you can use good ol' XML instead.

ameen

You need to use the spring interface FactoryBean.

Interface to be implemented by objects used within a BeanFactory which are themselves factories. If a bean implements this interface, it is used as a factory for an object to expose, not directly as a bean instance that will be exposed itself.

Implement the interface and declare a bean for it. For example :

@Component
class MyStaticFactoryFactoryBean implements FactoryBean<MyStaticFactory>
{
    public MyStaticFactory getObject()
        MyStaticFactory.getObject();
    }
    public Class<?> getObjectType() {
        return MyStaticFactory.class;
    }
    public boolean isSingleton() {
        return true;
    }
}

Through @Component and component scanning, this class will be discovered. Spring will detect that it is a FactoryBean and expose the object you return from getObject as a bean (singleton if you specify it).

Alternatively, you can provide a @Bean or <bean> declaration for this FactoryBean class.

Bean:

 public class MyObject {

        private String a;

        public MyObject(String a) {
            this.a = a;
        }

        @Override
        public String toString() {
            return a;
        }
    }

FactoryBean:

@Component
public class MyStaticFactory implements FactoryBean<MyObject> {


    @Override
    public MyObject getObject() throws Exception {
        return new MyObject("StaticFactory");
    }

    @Override
    public Class<?> getObjectType() {
        return MyObject.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

}

Use:

@Component
public class SomeClass{


    @Autowired
    MyObject myObject;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!