@Bean在具有@Configuration的类中并且没有它 [英] @Bean inside class with @Configuration and without it

查看:490
本文介绍了@Bean在具有@Configuration的类中并且没有它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring 3.0中有一个@Bean批注.它允许直接在Java代码中定义Spring bean.浏览Spring参考时,我发现了使用此批注的两种不同方式-用@Configuration批注的内部类和没有此批注的内部类.

There is a @Bean annotation in Spring 3.0. It allows to define a Spring bean directly in a Java code. While browsing Spring reference I found two different ways of using this annotation - inside class annotated with @Configuration and inside class which doesn't have this annotation.

本节包含以下代码:

@Component
public class FactoryMethodComponent {

   @Bean @Qualifier("public")
   public TestBean publicInstance() {
      return new TestBean("publicInstance");
   }

   // omitted irrelevant method
}

And here we could see a very similar piece of code, but now @Configuration is in the place:

@Configuration
public class AppConfig {
   @Bean
   public MyService myService() {
      return new MyServiceImpl();
   }
}

以前的参考资料部分包含以下说明:

Former section of reference contains following explaination:

Spring组件中@Bean方法的处理方式与Spring @Configuration类中的@Bean方法不同.区别在于,使用CGLIB不会增强@Component类,以拦截方法和字段的调用. CGLIB代理是调用@Configuration类中的方法或@Bean方法中的字段的方法,用于创建Bean元数据引用来协作对象.不能使用普通的Java语义来调用方法.相反,在@Component类@Bean方法中调用方法或字段具有标准的Java语义.

但是CGLIB是一种内部东西,应用程序开发人员不应该意识到(当然,在理想的世界中).据我了解,在这两种情况下,Spring均调用以@Bean注释的方法来创建Spring bean,在这两种情况下,这些实例均被注入到协作者中.

But CGLIB is a kind of internal stuff which application developer shouldn't be aware of (in a ideal world, of course). As I understand in both cases Spring invokes method annotated with @Bean to create Spring bean, in both cases these instances are injected to collaborators.

所以我的问题是在这两种情况下,对我来说,作为应用程序开发人员有什么区别?

So my question is what is the difference for me as an application developer between this two cases?

推荐答案

不同之处在于,使用@Configuration可以从另一个调用一个@Bean方法并获取一个完全初始化的实例,如下所示:

The difference is that with @Configuration you can call one @Bean method from another and get a fully initialized instance, as follows:

public class Foo {
    @Value("Hello, world!")
    public String value;
}

@Configuration
public class Config {
    @Bean
    public Foo createFoo() {
        Foo foo = new Foo();
        System.out.println(foo.value); // Prints null - foo not initialized yet
        return foo;
    }

    @Bean
    public Bar createBar() {
        Foo foo = createFoo();
        System.out.println(foo.value); // Prints Hello, world! - foo have been initialized by the interceptor
        return new Bar(foo);
    }
}

这篇关于@Bean在具有@Configuration的类中并且没有它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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