相似的,创建 maven 工程,配置pom.xml 文件,具体可以参考上一篇博文:
然后我们在 src/main/java
下创建一个新的package : cn.itcast.xmlanno
, 并在当前包下创建 BookDao.java, OrdersDao.java:
BookDao.java:
package cn.itcast.xmlanno;public class BookDao { public void book(){ System.out.println("book......"); } }
OrdersDao.java:
package cn.itcast.xmlanno;public class OrdersDao { public void buy(){ System.out.println("ordersdao......"); } }
在 resources 下创建 applicationContext.xml,同时写入注解和配置文件方式 :
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here --> <context:component-scan base-package="cn.itcast"></context:component-scan> <bean id="bookDao" class="cn.itcast.xmlanno.BookDao"></bean> <bean id="bookService" class="cn.itcast.xmlanno.BookService"></bean> <bean id="ordersDao" class="cn.itcast.xmlanno.OrdersDao"></bean></beans>
在 cn.itcast.xmlanno
下创建 BookService.java, 通过注解方式得到BookDao 和 OrdersDao 对象:
package cn.itcast.xmlanno;import javax.annotation.Resource;public class BookService { //得到BookDao 和 OrdersDao 对象 @Resource(name = "bookDao") private BookDao bookDao; @Resource(name = "ordersDao") private OrdersDao ordersDao; public void add(){ System.out.println("add........"); bookDao.book(); ordersDao.buy(); } }
我们创建一个测试类 TestUser.java,来进行测试:
package cn.itcast.xmlanno;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestUser { @Test public void TestBook(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); BookService bookService = (BookService) context.getBean("bookService"); bookService.add(); } }
运行测试文件,输出下列结果:
原文出处:https://www.cnblogs.com/weixuqin/p/9501631.html