- @Bean(方法註解)
@Bean的作用:初始化的時候創建對象,並放到IOC容器中。
以下通過一個例子說明:
1、定義一個類
public class TestBean {
public String testBean() {
return "@Bean";
}
}
2、使用@Bean【Java配置】,聲明該方法返回的是一個對象,並由spring的IOC統一管理(相當於spring的<bean>
標籤【xml配置】,也相當於@Component、@Service【註解配置】等,這裏做了一個三大配置的簡單說明)
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public TestBean testBean() {
return new TestBean();
}
}
3、通過@Bean註冊到了IOC容器中,@Autowired就能注入成功,即不需要手動創建TestBean對象就能調用其testBean()方法。
@RestController
public class TestBeanStart {
@Autowired
TestBean testBean;
@RequestMapping("/testBean")
public String testBeanStart() {
return testBean.testBean();
}
}
- @Configuration(類註解)
@Configuration聲明該類需要被初始化(也就是項目啓動的時候,該類中的方法就已經被執行),@Bean要跟@Configuration搭配使用,以上代碼中沒有出現@Configuration是因爲@SpringBootApplication註解包含了@Configuration,如下(源碼):
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}
如果不想把這部分代碼寫在啓動類中,@Configuration就能用上了,如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JavaConfig {
@Bean
public DemoService demoService(){
return new DemoService();
}
}
如有不足,望指點一二,謝謝。