手记

Spring 一二事(8) - annotation 形式的 MVC

2018-05-10 13:55:203745浏览

风间影月

10实战 · 54手记 · 8推荐
1 <!-- 
2            component:把一个类放入到spring容器中,该类就是一个component
3            在base-package指定的包及子包下扫描所有的类
4     -->
5     <context:component-scan base-package="com.lee.spring012.scan.mvc.annotation"></context:component-scan>

IStuDAO.java

1 package com.lee.spring012.scan.mvc.annotation;
2 
3 public interface IStuService {
4     public void saveStu();
5 }

PersonAction.java

package com.lee.spring012.scan.mvc.annotation;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Controller
@Scope("prototype")        // action为多例
public class PersonAction {

    @Resource
    public IStuService stuServiceImpl;

    public void displaySave() {
        System.out.println("mvc action: saving stu...");
        stuServiceImpl.saveStu();
    }

}

StuDAOImpl.java

package com.lee.spring012.scan.mvc.annotation;

import org.springframework.stereotype.Repository;

@Repository
public class StuDAOImpl implements IStuDAO {

    @Override
    public void saveStu() {
        System.out.println("mvc dao: saving stu...");
    }

}

StuServiceImpl.java

package com.lee.spring012.scan.mvc.annotation;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

@Service
public class StuServiceImpl implements IStuService {

    @Resource
    public IStuDAO stuDAOImpl;

    @Override
    public void saveStu() {
        System.out.println("mvc service: saving stu...");
        stuDAOImpl.saveStu();
    }

}

测试:

package com.lee.spring012.scan.mvc.annotation;

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

public class PersonTest {

    @Test
    public void testPersonAction() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-scan-mvc.xml");
        PersonAction person = (PersonAction)context.getBean("personAction");
        person.displaySave();
    }

}
2人推荐
随时随地看视频
慕课网APP