SpringBoot 中@Configuration 和@Component 注解的区别
使⽤
@Configuration和@Component都是使⽤于配置类上以代替XML⽂件中<beans>标签;
@Configuration是@Component的扩展,同样类似的扩展还有@Repository、@Service、@Controller、@RestController等等,⽽后⾯四个都是⽤于传统三层架构中使⽤的注解;
在被@Configuration注解的类中所有带有@Bean注解的⽅法都会被CGLib动态代理,⽽后每次调⽤这些⽅法时返回的都是第⼀次返回的实例;
被@Configuration标记的类不能是final类,不能是本地类、访问修饰符也不能是private。
测试区别
上⾯说了被@Configuration注解的类中所有带有@Bean注解的⽅法都会被CGLib动态代理并在第⼀次调⽤之后的每次调⽤时从BeanFactory中返回相同的实例,⽽@Component注解则不会。下⾯的例⼦展⽰了其区别:
编辑配置类
通过两个实体类测试,School属性包括(String)addr和(Student)student,Student属性有(String)name和(String)age:
编辑控制层⽤于测试分别通过注⼊⽅式实例化⼀个school和⼀个student对象,再判断school中的student对象与刚刚注⼊的student对象是否是⼀个对象://
选择配置注解
@Configuration
//@Component
public class TestConfiguration {
//⽣成shool 实例的⽅法
@Bean
public School school () {
School school = new School ();
school .setAddr ("");
school .setStudent (student ()); //这⾥调⽤student()新建⼀个对象给school
return school ;
}
//⽣成student 实例的⽅法
@Bean
public Student student () {
Student student = new Student ();
student .setName ("xiaoming");
student .setAge (18);
return student ;
}
}
发送请求查看结果
修改注解为@Component
resource和autowired注解的区别
发送请求再次查看结果
@RestController @RequestMapping("/")
public class TestController {
@Autowired
private School school ; //注⼊school
@Autowired
private Student student ; //注⼊student
@RequestMapping("/test")
public String test () {
if (school .getStudent () == student ) { //判断是否是同⼀个对象
return "同⼀个student 对象";
} else {
return "不同的student 对象";
}
}
}//
选择配置注解
/
/@Configuration
@Component
public class TestConfiguration {
//⽣成shool 实例的⽅法
@Bean
public School school () {
School school = new School ();
school .setAddr ("");
school .setStudent (student ()); //这⾥调⽤student()新建⼀个对象给school
return school ;
}
/
/⽣成student 实例的⽅法
@Bean
public Student student () {
Student student = new Student ();
student .setName ("xiaoming");
student .setAge (18);
return student ;
}
}
修改
如果想在@Component注解的类中实现每次返回相同的实例可通过@Autowired先将student注⼊到⼀个对象,之后在给school赋值的时候使⽤这个student对象:
继续查看结果
//选择配置注解
/
/@Configuration
@Component
public class TestConfiguration {
@Autowired
private Student stu ;
//⽣成shool 实例的⽅法
@Bean
public School school () {
School school = new School ();
school .setAddr ("");
school .setStudent (stu ); //这⾥使⽤注⼊的stu
return school ;
}
//⽣成student 实例的⽅法
@Bean
public Student student () {
Student student = new Student ();
student .setName ("xiaoming");
student .setAge (18);
return student ;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论