Spring 3 @Component 和静态工厂方法 [英] Spring 3 @Component and static factory method

查看:36
本文介绍了Spring 3 @Component 和静态工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我正在编写一个静态工厂方法来创建对象,我如何为该工厂类使用@Component"注释并指示(带有一些注释)应该调用的静态工厂方法来创建该对象的 bean班级?以下是我的意思的伪代码:

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

推荐答案

恐怕您目前无法执行此操作.然而,Java 配置非常简单:

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()
    }

}

在这种情况下 MyStaticFactory 不需要任何 Spring 注释.当然,您可以改用好的 ol' XML.

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

这篇关于Spring 3 @Component 和静态工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆