
package com.study.dao;
public interface BookDao {
void save();
}
package com.study.dao.impl;
import com.study.dao.BookDao;
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("BookDaoImpl...");
}
}
package com.study.service;
public interface BookService {
void save();
}
package com.study.service.impl;
import com.study.dao.BookDao;
import com.study.service.BookService;
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public void save() {
bookDao.save();
System.out.println("BookServiceImpl...");
}
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
}
注意:
<?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.study.dao.impl.BookDaoImpl"></bean>
<bean id="bookService" class="com.study.service.impl.BookServiceImpl" autowire="byType">
</bean>
<!-- 第一种按类型autowire="byType",id="bookDao" 则可以不写-->
<!-- 第二种按名称autowire="byName",如果id="bookDao1",则报错-->
</beans>
import com.study.dao.BookDao;
import com.study.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService service = app.getBean(BookService.class);
service.save();
}
}
/*
BookDaoImpl...
BookServiceImpl...
*/