Bean的装配方式
1.基于XML的装配(设值注入和构造注入)
设值注入要求一个Bean满足以下两点要求:
-
Bean类必须提供一个默认的无参构造方法
-
public class User {
private String name;
private Integer password;
private List<String> list;
public User() {
}
public User(String name, Integer password, List<String> list) {
this.name = name;
this.password = password;
this.list = list;
}
public class XmlBeanAssembleTest {
public static void main(String[] args) {
String xmlPath = "com/itheima/assemble/beans5.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
System.out.println(applicationContext.getBean("user1"));
System.out.println(applicationContext.getBean("user2"));
}
}
2.基于Annotation的装配(推荐)
一些常用的注解:
@Repository:用于将数据访问层(Dao层)的类标识为Spring中的Bean
@Service:用于将业务层(Service层)的类标识为Spring中的Bean
@Controller:用于将控制层(如Spring MVC中的Controller层)的类标识为Spring中的Bean
@Autowired:用于对Bean的属性变量、属性的setter方法及构造方法进行标注,配合对应的注解处理器完成Bean的自动装配工作,默认按照Bean的类型进行装配
@Resource:作用和@Autowired一样,但默认按照Bean实例名称装配
public interface UserDao {
public void save();
}
public interface UserService {
public void save();
}
public class AnnotationAssembleTest {
public static void main(String[] args) {
String xmlPath = "com/itheima/annotation/beans6.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserController userController = (UserController) applicationContext.getBean("userController");
userController.save();
}
}
3.自动装配
Spring的<bean>元素中包含一个autowire属性,可以通过该属性的属性值进行自动装配Bean,常用的属性值有byName、byType
浙公网安备 33010602011771号