SSM-Spring-Spring装配Bean-通过注解装配Bean-自动装配@Autowired
自动装配是由Spring自己发现对应的Bean,自动完成装配工作的方式, 用到一个十分常用的注解@Autowired,Spring会根据类型去寻找定义的Bean然后将其注入。
接口:
public interface RoleService2 {
public void printRoleInfo();
}
实现类:
@Component("RoleService2")
public class RoleServiceimpl2 implements RoleService2 {
//属性required = false,表示在Spring容器中没有注册,也不会报错,可有可无的含义
//什么内容都不配置,默认按类型注入
@Autowired
private Role role=null;
//set and get...
public void printRoleInfo() {
System.out.println("id"+role.getId());
System.out.println("roleName"+role.getRoleName());
System.out.println("note"+role.getNote());
}
}
Ioc容器也会寻找失败,默认情况会抛出异常,可以通过设置required = false来改变他,代表Bean中找不到对应的类型,允许不注入。那么字段为空
还可以配置方法,常见的Bean的setter方法也可以使用它来完成注入:
@Autowired
public Long getId() {
return id;
}
这样能满足:约定优于配置的原则,增强程序的健壮性,不过遇到复杂的情况,肯能不能进行自动装配