IDEA中Spring的配置使用
- 1.首先创建JavaEE Web Application项目,勾选Spring,Libraries选择Set up library later。(有spring jar包的前提下,没有jar包选择Download)
- 2.项目目录结构
- 3.把lib包中struts2的所有jar包选中,右键,选择Add as Library
- 4.Ctrl+Alt+Shift+s打开项目结构,进行配置
-
5.一个简单的spring example
-
5.1编写一个UserDao接口
package pers.wpc.dao;
public interface UserDAO {
public void save();
} -
5.2编写实现类UserDao
UserDao.java
package pers.wpc.dao.impl;
import pers.wpc.dao.UserDAO;
public class UserDao implements UserDAO {
@Override
public void save() {
System.out.println("save user");
}
}
- 5.3编写测试类
UserService.java
package pers.wpc.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pers.wpc.dao.UserDAO;
public class UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO){
this.userDAO = userDAO;
}
public void addUser(){
userDAO.save();
}
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContent.xml");
UserService us =(UserService)ac.getBean("UserService");
us.addUser();
}
}
- 5.4在src下编写一个applicationContext.xml配置文件并进行依赖注入配置,xml需导入Model–>Spring中
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="UserDAO" class="pers.wpc.dao.impl.UserDao"/>
<bean id="UserService" class="pers.wpc.test.UserService">
<property name="userDAO">
<ref bean="UserDAO"/>
</property>
</bean>
</beans>
- 5.5测试