关于Spring注入之web经典三层架构的耦合

在此重新叙述关于set方法进行注入和@Autowired注解进行注入的问题:

set方法进行注入的时候,可以将任何类型进行注入,普通类型,引用类型和复杂类型,在applicationContext.xml配置文件中进行

然后可以将引用类型进行注入,而@Autowired也可以在类的内部对其他类进行注入先根据byName,再根据byType

在此根据注入举个关于耦合强度够高的dao层,service层和web层之间的具体连接

在dao层中:

package dao;

import pojo.User;

public interface UserDao {
  public void addUser(User user);
}

package dao;

import pojo.User;

public class UserDaoImpl implements UserDao {

    public void addUser(User user) {
        // TODO Auto-generated method stub
        System.out.println("新增一个用户:"+user);
    }  
}
在pojo层中:

package pojo;

public class User {
  private String name;
  private int age;
public User(String name, int age) {
    super();
    this.name = name;
    this.age = age;
}
@Override
public String toString() {
    return "User [name=" + name + ", age=" + age + "]";
}
  
}

在service层中:

package service;

import pojo.User;

public interface UserService {
  public void addUser(User user);
}

package service;

import dao.UserDao;
import pojo.User;

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void addUser(User user) {
        // TODO Auto-generated method stub
        userDao.addUser(user);
    }

}

在web层中:

package web;

import pojo.User;
import service.UserService;

public class UserServlet {
    private UserService userService;
    
  public void setUserService(UserService userService) {
        this.userService = userService;
    }

  public void addUser(User user)
  {
      userService.addUser(user);
  }
}
applicationContext.xml中:


     
     
   

   
   
     
   

   
     
   

Test测试类:

package test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import pojo.User;
import web.UserServlet;

public class TestSpring {
 @Test
 public void test01(){
     ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
     User user = (User) context.getBean("user");
     UserServlet userServlet = (UserServlet) context.getBean("userServlet");
    userServlet.addUser(user);
 }
}
 

你可能感兴趣的:(java)