Spring Java配置:仅指定类 [英] Spring Java config : Specify class only

查看:158
本文介绍了Spring Java配置:仅指定类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些基于Xml的spring配置转移到基于Java的过程中.

I'm in the process of moving some Xml-Based spring config over to Java-based.

以前,我根据情况有意识地将Xml <bean class='foo' />声明与@Component映射混合在一起,以作为记录非显而易见的bean的一种方法.

Previously, I've consciously mixed Xml <bean class='foo' /> declarations with @Component mappings on a case-by-case basis, as a means of documenting non-obvious beans.

一个典型的用例是,如果我声明将修改spring本身行为的bean,我将明确声明它们,而不是让它们被发现,纯粹是为了提高配置文件的清晰度.

A typical use case would be if I'm declaring beans that will modify the behaviour of spring itself, I'll declare these explicitly, rather than let them be discovered, purely to improve the clarity of the config file.

但是,这些bean通常需要一定程度的@Autowiring.如果我自己在Java配置中将bean设置为new,则我将负责执行此连接-这是没有意义的.

However, often these beans will need a degree of @Autowiring. If I new the bean up myself within a Java config, I become responsible for performing this wiring -- which is pointless.

是否有一个纯Java配置选项可以显式地向Spring提供一个类,并让它管理实例化?

Is there a pure Java configuration option that explicitly provides a class back to Spring, and let's it manage the instantiation?

即:

上课:

public class MyFunkySpringBean implements InitializingBean {
    @Autowired Foo foo;
}

在XML配置中,这将简单地声明为:

In XML config, this would be declared as simply as:

<bean class="MyFunkySpringBean" />

是否有Java语法的等效项,我可以在其中将bean类显式声明为Spring,但不负责提供实际实例,而是将其留给Spring.

Is there an equivalent in Java syntax, where I can explicitly declare the bean class to Spring, but not be responsible for providing the actual instance -- leaving that to Spring.

例如:

@Configuration 
public class MyAppConfig {

    // Explictly provide the class, not the instance to Spring
    @Bean
    public MyFunkySpringBean funkyBean; // No instance -- it's up to Spring to build
}

要清楚,我不要想要这样做:

To be clear, I don't want to have to do this:

@Configuration 
public class MyAppConfig {

    @Bean
    public MyFunkySpringBean funkyBean() {
         MyFunkySpringBean bean = new MyFunkySpringBean();
         bean.foo = new Foo();
         // other dependencies go here
         return bean;
    }

}

Spring内是否存在这样的设施?

Does facility like this exist within Spring?

推荐答案

在Spring的较新版本(从4.2版本开始)中,您可以使用org.springframework.context.annotation.Import例如

In newer versions of Spring (as of 4.2) you can use org.springframework.context.annotation.Import e.g.

@Configuration
@Import(MyFunkySpringBean.class)
public class MyAppConfig {
   ... other config ...
}

这篇关于Spring Java配置:仅指定类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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