1.dao
package com.dao;
public interface UserDao {
public void print();
}
2.daoImpl
package com.dao;
public class UserDaoImpl implements UserDao{
@Override
public void print() {
System.out.println("userdaoImpl被调用");
}
}
3.service
package com.service;
public interface UserService {
public void print();
}
4.serviceImpl
package com.service;
import com.dao.UserDao;
public class UserServiceImpl implements UserService{
private UserDao userdao1;
public void setUserdao(UserDao userdao) {
this.userdao1 = userdao;
}
@Override
public void print() {
userdao1.print();
}
}
5.配置文件
<?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-4.3.xsd">
<!-- <bean id="userdao" class="com.dao.UserDaoImpl"/>
<bean id="userservice" class="com.service.UserServiceImpl">
<property name="userdao" ref="userdao"></property>
</bean> -->
<!-- 当时通过名字使用自动装配时 userservice会自动找set函数名字一样的bean,而与属性名无关
当定义在最上方的beans里面时,即装配所有的bean
-->
<bean id="userdao" class="com.dao.UserDaoImpl"/>
<bean id="userservice" class="com.service.UserServiceImpl" autowire="byName"></bean>
</beans>
6.测试类
package com.Test;
import javax.faces.application.Application;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.service.UserService;
import com.service.UserServiceImpl;
public class test {
public static void main(String [] arges) {
ApplicationContext context=new ClassPathXmlApplicationContext("config.xml");
UserService userService=(UserServiceImpl) context.getBean("userservice");
userService.print();
}
}