一、作用
@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
二、使用方法
项目整体结构↓
1.引入依赖
<!--基础依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--工具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
2.创建bean
图书bean
package com.cxstar.bean;
import lombok.Data;
@Data
public class Book {
private String title;
private String author;
private String publisher;
public Book() {}
public Book(String title, String author, String publisher) {
this.title = title;
this.author = author;
this.publisher = publisher;
}
}
期刊bean
package com.cxstar.bean;
import lombok.Data;
@Data
public class Periodical {
private String title;
private String editor;
private String organizer;
public Periodical() {}
public Periodical(String title, String editor, String organizer) {
this.title = title;
this.editor = editor;
this.organizer = organizer;
}
}
3.创建配置类
package com.cxstar.config;
import com.cxstar.bean.Book;
import com.cxstar.bean.Periodical;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration // 标记为配置类
public class MyConfig {
@Bean // 给容器添加组件,以方法名作为组件的id,返回类型就是组件的类型,返回值就是组件在容器中的实例
public Book defaultBook() {
return new Book("白夜行", "东野圭吾", "人民邮电出版社");
}
@Bean // 给容器添加组件,以方法名作为组件的id,返回类型就是组件的类型,返回值就是组件在容器中的实例
public Periodical defaultPeriodical() {
return new Periodical("时代经贸", "赵建锁", "北京财贸职业学院");
}
}
4.创建测试类
package com.cxstar;
import com.cxstar.config.MyConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ConfigurationApplicationTests {
@Autowired
MyConfig myConfig;
@Test
void contextLoads() {
System.out.println(myConfig.defaultBook());
System.out.println(myConfig.defaultPeriodical());
}
}
输出↓
三、注意事项
@Configuration注解的配置类有如下要求:
1.@Configuration不可以是final类型;
2.@Configuration不可以是匿名类;
3.嵌套的configuration必须是静态类。