环境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(“参数”)可以更改别名