beans.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"
xmlns:context="http://www.springframework.org/schema/context"
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">
<context:annotation-config />
<context:component-scan base-package="com.bjsxt"/>
</beans>
UserServiceTest.java:
package com.bjsxt.service;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.bjsxt.model.User; //Dependency Injection
//Inverse of Control
public class UserServiceTest { @Test
public void testAdd() throws Exception {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserService service = (UserService)ctx.getBean("userService");
service.add(new User());
ctx.destroy();
}
}
UserService.java:
package com.bjsxt.service;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User; @Component("userService")
public class UserService {
private UserDAO userDAO;
public void init() {
System.out.println("init");
}
public void add(User user) {
userDAO.save(user);
}
public UserDAO getUserDAO() {
return userDAO;
} @Resource(name="u")
public void setUserDAO( UserDAO userDAO) {
this.userDAO = userDAO;
}
public void destroy() {
System.out.println("destroy");
}
}
UserDAOImpl.java:
package com.bjsxt.dao.impl;
import org.springframework.stereotype.Component;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;
@Component("u")
public class UserDAOImpl implements UserDAO {
public void save(User user) {
//Hibernate
//JDBC
//XML
//NetWork
System.out.println("user saved!");
}
}