環境Idea + maven,相關依賴
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
- @Configuration註解相當於原先spring的xml配置文件,用配置類代替配置文件
- @Bean註解 在配置了@Configuration的配置類中使用
- @Bean註解配置在方法名上,在IOC容器中的名稱就是方法名
- 改別名則傳入別名例如@Bean("別名")
完整例子
package bean;
public class HelloWorld {
String hello="Hello demo";
@Override
public String toString() {
return "HelloWorld{" +
"hello='" + hello + '\'' +
'}';
}
}
package config;
import bean.HelloWorld;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config {
@Bean("hello")
public HelloWorld hello(){
return new HelloWorld();
}
}
單元測試
package config;
import bean.HelloWorld;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.Assert.*;
public class ConfigTest {
@Test
public void test1(){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
HelloWorld hello = (HelloWorld) applicationContext.getBean("hello");
System.out.println(hello);
}
}
輸出結果
通過修改@Bean(“參數”)可以更改別名