Spring 3 @Component and static factory method

亡梦爱人 提交于 2019-12-29 08:27:13

问题


If I'm writing a static factory method to create objects, how do I use the '@Component' annotation for that factory class and indicate (with some annotation) the static factory method which should be called to create beans of that class? Following is the pseudo-code of what I mean:

@Component
class MyStaticFactory
{
    @<some-annotation>
    public static MyObject getObject()
    {
        // code to create/return the instance
    }
}

回答1:


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.




回答2:


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.




回答3:


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;
}


来源:https://stackoverflow.com/questions/9598829/spring-3-component-and-static-factory-method

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