一。引入jar包
spring.jar commons-loggion-1.0.4.jar
二。springIOC,是把一个对象注入到另一个对象。
处理接口
接口实现
服务层
@Autowired 注释是自动注入配置文件存在的与当前类属性类型一致的类(默认bytype),
@Qualifier("userDAOImpl")是指定配置文件中存在的bean的ID或name
也可用@Resource(name="employDAOImpl"),@Resource默认配置文件中存在的bean的ID或name
实体类
spring的application.xml配置(使用annotation的autoware自动注入)
配置<context:annotation-config />初始化annotation组件及其它功能
配置javabean
测试
ClassPathXmlApplicationContext方法不写路径,则默认读取项目根路径src下applicationContext.xml文件
测试结果
[quote]
me haha ---haha!
[/quote]
spring.jar commons-loggion-1.0.4.jar
二。springIOC,是把一个对象注入到另一个对象。
处理接口
package com.job.dao;
import com.job.model.User;
public interface UserDAO {
public void save(User u);
}
接口实现
package com.job.dao;
import com.job.model.User;
public class UserDAOImpl implements UserDAO{
@Override
public void save(User u) {
System.out.println(u.getUsername()+"---haha!");
}
}
服务层
public class UserService {
private UserDAO userDAO;
public void add(User u){
this.userDAO.save(u);
}
public UserDAO getUserDAO() {
return userDAO;
}
@Autowired
public void setUserDAO(@Qualifier("userDAOImpl")UserDAO userDAO) {
this.userDAO = userDAO;
}
}
@Autowired 注释是自动注入配置文件存在的与当前类属性类型一致的类(默认bytype),
@Qualifier("userDAOImpl")是指定配置文件中存在的bean的ID或name
也可用@Resource(name="employDAOImpl"),@Resource默认配置文件中存在的bean的ID或name
实体类
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
spring的application.xml配置(使用annotation的autoware自动注入)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" >
<context:annotation-config />
<bean id="userService" class="com.job.service.UserService" >
</bean>
<bean id="userDAOImpl" class="com.job.dao.UserDAOImpl" lazy-init="true" >
</bean>
<bean id="employDAOImpl" class="com.job.dao.EmployDAOImpl" lazy-init="true" >
</bean>
</beans>
配置<context:annotation-config />初始化annotation组件及其它功能
配置javabean
测试
public class UserServiceTest {
@Test
public void test(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = (UserService)ac.getBean("userService");
User u = new User();
u.setUsername("me haha ");
service.add(u);
}
}
ClassPathXmlApplicationContext方法不写路径,则默认读取项目根路径src下applicationContext.xml文件
测试结果
[quote]
me haha ---haha!
[/quote]