大家好呀,今天跟大家分享一个IOC容器小案例,希望对大家有所帮助哦!喜欢记得点个关注哦,更多精彩等你哦。
一、首先我们来创建一个service层包,在包中再建一个UserService类.
package service;
import dao.UserDao;
import dao.UserDaoimpl;
public class UserService {
//创建UserDao属性,生成set方法。
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
private UserDao userDao;
public void add(){
System.out.println("你好,我是服务层哦!");
//创建UserDao对象
// UserDao userDao=new UserDaoimpl();
userDao.update();
}
}
二、然后在建一个dao包,在包中分别建一个UserDao接口类和继承接口的UserDaoiml类。
package dao;
public interface UserDao {
public void update();
}
package dao;
public class UserDaoimpl implements UserDao{
@Override
public void update() {
System.out.println("你好,我是接口层哦");
}
}
三、接下来就是在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="userService" class="service.UserService">
<property name="userDao" ref="userdaoIml"/>
</bean>
<bean id="userdaoIml" class="dao.UserDaoimpl">
</bean>
</beans>
四、最后当然是建立一个测试类啦。
package TestSpring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;
public class testBean {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("Bean1.xml") ;
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}