设计模式 - 没有DI框架的webapp

时间:2014-06-23 10:15:00

标签: java design-patterns web-applications dependency-injection

我需要在没有依赖注入框架的情况下实现servlet 3.0 webapp。哪种解决方案是最好的练习? (在性能/内存使用和可伸缩性方面)

1)DAO和服务层的静态方法

@WebServlet("/welcome")
public class MyController extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {

        MyService.doSomething(/*args*/);
    }
}

public class MyService {

    public static void doSomething(/*args*/) {
        MyDAO.crud(/*args*/);
    }
}

public class MyDAO {

    public static void crud(/*args*/) {
        //...
    }
}

2)接口

@WebServlet("/welcome")
public class MyController extends HttpServlet {

    private MyService myService;

    public MyController() {
        super();
        if (myService != null) {
            myService = new MyServiceImpl();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {

        myService.doSomething(/*args*/);
    }
}

public interface MyService {

    void doSomething(/*args*/);
}

public class MyServiceImpl implements MyService {

    private MyDAO myDAO;

    public MyServiceImpl() {
        if (myService != null) {
            myDAO = new MyDAOImpl();
        }
    }

    @Override
    public void doSomething(/*args*/) {
        myDAO.crud(/*args*/);
    }
}

public interface MyDAO {

    void crud(/*args*/);
}

public class MyDAOImpl implements MyDAO {

    @Override
    public void crud(/*args*/) {
        //...
    }
}

3)别的东西......

感谢。

3 个答案:

答案 0 :(得分:1)

最好将MyService中的MyDAOapplication同为stateless。 您可以将它们都设为singletons(这是注入default的所有spring beans范围内的任何方式),并在controller中使用它。由于stateless concurrency问题没有问题。

答案 1 :(得分:0)

不要使用静态方法,因为它不能被模拟或注入。虽然假设dao不在内存中(并且本身不是有状态的),但它将是线程安全的。

为什么没有框架就必须这样做?

答案 2 :(得分:0)

查看是否要实现单例而不是创建

  

类public class FetchBean {

static Map<String, Object> beans;

static {
    beans = new HashMap<String, Object>();
}

public static Object getBean(Class bean) {
    try {            
        if (!beans.containsKey(bean.getName())) {
            Object instance = bean.newInstance();                
            beans.put(bean.getName(), instance);
        }
        return beans.get(bean.getName());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

public static void main(String[] args) {
    Person person = (Person) FetchBean.getBean(Person.class);
    person.setName("Taher");
    System.out.println(person.getName());
    Person person2 = (Person) FetchBean.getBean(Person.class);
    person2.setName("Tinwala");
    System.out.println(person2.getName());
} }
public class Person {

    public Person() {
        System.out.println("In person");
    }

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}