1.BookDaoImpl.class
这个类的对象将会被自动装配注入到BookServiceImpl类里面。
BookServiceImpl类里面讲调用BookDaoImpl类的方法。
package com.oxygen.dao.impl; import com.oxygen.dao.BookDao; public class BookDaoImpl implements BookDao { public void save() { System.out.println("Book Dao Save..."); } }
2.BookServiceImpl.class
此类和BookDaoImpl有依赖关系.
注意:在使用autowaire自动装配时,必须有个setter方法,也即setter注入。
package com.oxygen.service.impl; import com.oxygen.dao.BookDao; import com.oxygen.service.BookService; public class BookServiceImpl implements BookService { private BookDao bookDao; //使用autowaire,需要有setter方法 //如果没有setter,会报空指针异常 public void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } public void save() { System.out.println("Book Service save..."); bookDao.save(); } }
3.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="bookDao" class="com.oxygen.dao.impl.BookDaoImpl"/> <bean id="bookService" class="com.oxygen.service.impl.BookServiceImpl" autowire="byType"/> </beans>
4.测试:
package com.oxygen; import com.oxygen.service.BookService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); BookService bookService = (BookService) context.getBean("bookService"); bookService.save(); } }
标签:xml,oxygen,Spring,autoware,bookDao,import,save,com,public From: https://www.cnblogs.com/majestyking/p/16816389.html