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

本文通过一个具体的示例介绍了如何使用 Spring 的注解扫描功能来实现 MVC 架构。示例包括了 Controller、Service 和 DAO 层的类定义,并展示了如何通过 @Controller、@Service 和 @Repository 注解将这些类注册到 Spring 容器中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 IStuDAO {
4     public void saveStu();
5 }

IStuService.java

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

PersonAction.java

 1 package com.lee.spring012.scan.mvc.annotation;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.context.annotation.Scope;
 6 import org.springframework.stereotype.Controller;
 7 
 8 @Controller
 9 @Scope("prototype")        // action为多例
10 public class PersonAction {
11 
12     @Resource
13     public IStuService stuServiceImpl;
14 
15     public void displaySave() {
16         System.out.println("mvc action: saving stu...");
17         stuServiceImpl.saveStu();
18     }
19 
20 }

StuDAOImpl.java

 1 package com.lee.spring012.scan.mvc.annotation;
 2 
 3 import org.springframework.stereotype.Repository;
 4 
 5 @Repository
 6 public class StuDAOImpl implements IStuDAO {
 7 
 8     @Override
 9     public void saveStu() {
10         System.out.println("mvc dao: saving stu...");
11     }
12 
13 }

StuServiceImpl.java

 1 package com.lee.spring012.scan.mvc.annotation;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.stereotype.Service;
 6 
 7 @Service
 8 public class StuServiceImpl implements IStuService {
 9 
10     @Resource
11     public IStuDAO stuDAOImpl;
12     
13     @Override
14     public void saveStu() {
15         System.out.println("mvc service: saving stu...");
16         stuDAOImpl.saveStu();
17     }
18 
19 }

测试

 1 package com.lee.spring012.scan.mvc.annotation;
 2 
 3 import org.junit.Test;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 
 7 public class PersonTest {
 8 
 9     @Test
10     public void testPersonAction() {
11         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-scan-mvc.xml");
12         PersonAction person = (PersonAction)context.getBean("personAction");
13         person.displaySave();
14     }
15 
16 }

github地址:https://github.com/leechenxiang/maven-spring001-helloworld

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值