日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

@Configuration 和 @Bean

發布時間:2024/9/20 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 @Configuration 和 @Bean 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. @Bean:

1.1 定義

從定義可以看出,@Bean只能用于注解方法和注解的定義。

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME)

1.2 spring文檔中對 @Bean的說明

The?@Bean?annotation is used to indicate that a method instantiates, configures and initializes a new object to be managed by the Spring IoC container.

For those familiar with Spring’s?<beans/>?XML configuration the?@Bean?annotation plays the same role as the?<bean/>element.?

用@Bean注解的方法:會實例化、配置并初始化一個新的對象,這個對象會由spring IoC 容器管理。

實例:

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

相當于在 XML 文件中配置

<beans><bean id="myService" class="com.acme.services.MyServiceImpl"/> </beans>

1.3 生成對象的名字:默認情況下用@Bean注解的方法名作為對象的名字。但是可以用 name屬性定義對象的名字,而且還可以使用name為對象起多個名字。

@Configuration public class AppConfig {@Bean(name = "myFoo")public Foo foo() {return new Foo();}} @Configuration public class AppConfig {@Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" })public DataSource dataSource() {// instantiate, configure and return DataSource bean...}}

1.4 @Bean 一般和 @Component或者@Configuration 一起使用。

@Component和@Configuration不同之處

(1)This method of?declaring inter-bean dependencies?only works when the?@Bean?method is declared within a?@Configurationclass. You cannot declare inter-bean dependencies using plain?@Component?classes.

在 @Component 注解的類中不能定義 類內依賴的@Bean注解的方法。@Configuration可以。

@Configuration public class AppConfig {@Beanpublic Foo foo() {return new Foo(bar());}@Beanpublic Bar bar() {return new Bar();}}

2. @Configuration:

2.1 定義

從定義看,用于注解類、接口、枚舉、注解的定義。

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME)

?2.2 spring 文檔說明

@Configuration?is a class-level annotation indicating?that an object is a source of bean definitions.?@Configuration?classes declare beans via public?@Bean?annotated methods.

@Configuration用于類,表明這個類是beans定義的源。

總結

以上是生活随笔為你收集整理的@Configuration 和 @Bean的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。