Spring AnnotationConfigApplicationContext
一.AnnotationConfigApplicationContext
Application大致分为三类:xmlApplicationContext,AnnotationConfigApplicationContext,WebApplicationContext。今天配置AnnotationConfigApplicationContext。
Annotation:注解,注解的作用是对类和方法的说明;
Config:配置;
ApplicationContext:应用程序上下文
PS:AnnotationConfigApplicationContext中的配置类相当于xml文件
二.配置Bean
1.新建配置类,添加@Configuration注解;
新建方法返回新建对象,并在方法上添加@Bean注解
配置类可添加@Autowired,@Inject,@Scope注解
import filmchart.entities.Film;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AnnotationConfig {
@Bean
public Films AnnotationConfig(){
return new Films();
}
}
配置@Configuration注解时的约束
1.配置类是non-final
2.配置类必须是非局部的
3.嵌套配置类声明为静态的
2.实体类
package filmchart.entities;
import org.springframework.stereotype.Component;
@Component
public class Films {
private int fId;
private String name;
private Double score;
@Autowired
private Writer writer;
public int getfId() {
return fId;
}
public void setfId(int fId) {
this.fId = fId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public Writer getWriter() {
return writer;
}
public void setWriter(Writer writer) {
this.writer = writer;
}
}
3.Test类
import filmchart.entities.Film;
import filmchart.entities.Films;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AnnotationTest {
AnnotationConfigApplicationContext context;
public AnnotationTest(){
context = new AnnotationConfigApplicationContext();
context.scan("filmchart");//通过指定包查询bean
context.refresh();//刷新
}
@Test
public void film(){
Films f1= context.getBean(Films.class);
Assert.assertNotNull(f1);
}
@Test
public void configBean(){
Film f1=(Film) context.getBean("film1");
Assert.assertEquals(1,f1.getId());
}
}