演示java類java
public class DemoService { public void doSomething(){ System.out.println("everything is all fine"); } }
演示配置spring
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import(DemoService.class)//在spring 4.2以前是不不支持的 public class DemoConfig { }
運行spa
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.wisely.spring4_2.imp"); DemoService ds = context.getBean(DemoService.class); ds.doSomething(); } }
輸出結果.net
everything is all fine
①註解@Bean的屬性initMethod, destroyMethod code
②接口InitializingBean, DisposableBeanxml
③註解@PostConstruct,@PreDestroy
都做用於一樣的兩個過程——初始化階段和銷燬階段對象
1.1 定義接口
從定義能夠看出,@Bean只能用於註解方法和註解的定義。ci
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME)
1.2 spring文檔中對 @Bean的說明element
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 { @Bean public 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... } }
@Bean 通常和 @Component或者@Configuration 一塊兒使用。
@Component和@Configuration不一樣之處
(1)This method of declaring inter-bean dependencies only works when the
@Bean
method is declared within a@Configuration
class. You cannot declare inter-bean dependencies using plain @Component
classes.
在 @Component 註解的類中不能定義 類內依賴的@Bean註解的方法。@Configuration能夠。
@Configuration可理解爲用spring的時候xml裏面的<beans>標籤
@Bean可理解爲用spring的時候xml裏面的<bean>標籤