Spring学习-13:Spring的XML和注解的结合使用

实际开发中使用XML还是注解?

XML:

bean的管理

注解:

注入属性的时候比较方便


两种方式的结合:一般使用XML注册bean,使用注解来进行属性注入。在applicationContext.xml中配置

举个简单的例子:

新建3个bean:

package com.js.demo4;

public class OrderDao {

}


package com.js.demo4;

public class CustomerDao {

}


package com.js.demo4;

public class CustomerService {
	private CustomerDao customerDao;
	private OrderDao orderDao;
	@Override
	public String toString() {
		return "CustomerService [customerDao=" + customerDao + ", orderDao="
				+ orderDao + "]";
	}
	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}
	public void setOrderDao(OrderDao orderDao) {
		this.orderDao = orderDao;
	}
	
}


配置applicationContext.xml:









	
	



编写测试类:

package com.js.demo4;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test4 {
	@Test
	public void demo(){
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext2.xml");
		CustomerService customerService = (CustomerService)applicationContext.getBean("customerService");
		System.out.println(customerService);
	}
}

运行结果,注入成功:


我们能不能修改配置方式,只在xml中注册bean,而将bean的属性注入使用注解来完成呢?

修改CustomerService:使用注解传入的属性就不在需要setter方法,也不再需要Component-scan,因为我们的bean全部在xml中配置,此处修改两个属性之一的orderDao:

package com.js.demo4;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class CustomerService {
	private CustomerDao customerDao;
	@Autowired
	@Qualifier("orderDao")
	private OrderDao orderDao;
	@Override
	public String toString() {
		return "CustomerService [customerDao=" + customerDao + ", orderDao="
				+ orderDao + "]";
	}
	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}
	
}

修改xml配置文件:









	



运行测试,成功。

Spring学习-13:Spring的XML和注解的结合使用_第1张图片








你可能感兴趣的:(Spring,Spring学习之路)