spring ioc 注解配置

要注意spring 版本与jdk的兼容性

applicationContext-resource.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.2.xsd ">
  <context:component-scan base-package="com.cdsxt" />
</beans>

base:

public interface BaseDao<T> {}

@Component("baseDao")
public class BaseDaoImpl<T> implements BaseDao<T> {
  private Class clazz;
  public BaseDaoImpl() {
    ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
    clazz =(Class) type.getActualTypeArguments()[0];
  }
  public Class getClazz() {
    return clazz;
  }
  public void setClazz(Class clazz) {
    this.clazz = clazz;
  }
}

action:

/**
* @Controller:专门注解 控制层 类
* @Service :专门注解 业务层类
* @Repository:专门注解持久层类
* @Component:可以注解任何类
* @Scope: 控制是否单例
* @Autowired 和 @Resource 都可以注解 被注入的属性
* @author Administrator
*
*/
@Controller
@Scope("prototype")
public class UserAction {
  @Autowired
  private UserService userService;
  public void add(){
    System.out.println("=======UserAction========");
    userService.add();
  }
  public UserService getUserService() {
    return userService;
  }
  public void setUserService(UserService userService) {
    this.userService = userService;
  }
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-resource.xml");
    UserAction u1 =(UserAction) context.getBean("userAction");
    u1.add();
  }
}

service:

public interface UserService {
  public void add();
}

@Service("userService")
public class UserServiceImpl implements UserService{
  @Autowired
  private UserDao userDao;
  @Override
  public void add() {
    System.out.println("=========UserServiceImpl============");
    userDao.add();
  }
  public UserDao getUserDao() {
    return userDao;
  }
  public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
  }
}

dao:

public interface UserDao extends BaseDao<User>{
  public void add();
}

@Repository("userDao")
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao{
  public void add() {
    System.out.println("=========UserDaoImpl==========");
  }
}

po:

public class User {}

上一篇:C# 传值和传引用 ( ref out in )


下一篇:python---协程 学习笔记