Bean的装配可以理解为依赖关系注入Bean的装配方式即Bean依赖注入的方式.Spring容器支持多种形式的Bean的装配方式,如基于XML的装配、基于注解(Annotation)的装配和自动装配(其中最常用的是基于注解的装配),接下来将对前两种进行详细讲解.
1.基于xml的装配
(1)创建Java类,提供有参,无参构造方法,以及属性的set方法.
package xml;
import java.util.List;
public class User {
private String username;
private Integer password;
private List<String> list;
public void setUsername(String username) {
this.username = username;
}
public void setPassword(Integer password) {
this.password = password;
}
public void setList(List<String> list) {
this.list = list;
}
public User(String username, Integer password, List<String> list) {
super();
this.username = username;
this.password = password;
this.list = list;
}
public User() {
super();
}
public User(String i) {
username = s;
}
@Override public String toString() { return "User{" + "username='" + username + '\'' + ", password=" + password + ", list=" + list + '}'; }}(2)配置xml
<bean id="user1" class="xml.User">
<constructor-arg index="0" value="tom"/>
</bean>
<bean id="user2" class="xml.User" >
<property name="username" value="cat"/>
</bean>
(3)测试类
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println(applicationContext.getBean("user1"));
System.out.println(applicationContext.getBean("user2"));
}
}
运行结果如下:
2.Annotation注解:
基于XML的装配可能会导致XML配置文件过于臃肿,给后续的维护和升级带来一定的困难。为此,Spring提供了对Annotation(注解)技术的全面支持。
(1)xml配置
<context:component-scan base-package="annotation" />
上面为自动扫描包下所有Bean.但是不会自动装配,在此结合注解使用.
(2)UserDao接口的配置(略)以及UserDaoImpl类:
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("userdao...save...");
}
}
(3)UserService接口的配置(略)以及UserServiceImpl类:
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource(name="userDao")
private UserDao userDao;
@Override
public void save() {
this.userDao.save();
}
}
(4)UserController@Controller("userController")
public class UserController {
@Resource(name="userService")
private UserService userService;
public void save(){
this.userService.save();
}
}
(5)测试类
public class Test1 {
public static void main(String[] args) {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserController userController = (UserController) applicationContext.getBean("userController");
userController.save();
}
}
运行结果如下:
(参考自:<<JavaEE企业级开发应用教程>>)