注解@Component、@Controller、@Service、@Repository的区别?
主题:注解@Component、@Controller、@Service、@Repository的区别?
Spring 2.5 中除了提供 @Component 注释外,还提供了几个特殊语义的注释:@Repository、@Service、@Controller。
其实,这三个注释和@Controller是等效的,由于Web应用程序现在采用了三层架构原理,为了层次更加鲜明,降低耦合度,又细分了一下,分别为:持久层、业务层、控制层。
注意:虽然目前这3 个注释和 @Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能,目的就是方便以后扩展功能。
@Component:泛指组件,当组件不好归类的时候,可以使用这个注解进行标注;
@Controller:用于标注控制层组件;
@Service:用于标注业务层组件;
@Repository:用于标注数据访问组件(持久层),即DAO组件。
-
@Controller
-
//为了对url进行分类管理,可以在这里定义根路径,最终访问的url是:根路径+子路径(窄化请求映射)
-
@RequestMapping("/items" )
-
public class ItemsController
-
{
-
......
-
}
-
@Service
-
public class LoginServiceImpl implements LoginService
-
{
-
......
-
}
-
@Repository
-
public class LoginDaoImpl implements LoginDao
-
{
-
......
-
}
它的作用和在xml文件中使用bean节点配置组件时一样的。要使用自动扫描机制,我们需要打开以下配置信息:
代码:
-
<?xml version="1.0" encoding="UTF-8"?>
-
<beans xmlns="http://www.springframework.org/schema/beans"
-
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
-
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
-
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
-
<!--
-
扫描该package下所有的类、方法、属性上面的注解
-
-->
-
<context:component-scan base-package="com.sunhui.iocDemo"></context:component-scan>
-
</beans>
1、component-scan标签默认情况下自动扫描指定路径下的包(含所有子包),将带有@Component、@Repository、@Service、@Controller标签的类自动注册到spring容器。对标记了 Spring's @Required、@Autowired、JSR250's @PostConstruct、@PreDestroy、@Resource、JAX-WS's @WebServiceRef、EJB3's @EJB、JPA's @PersistenceContext、@PersistenceUnit等注解的类进行对应的操作使注解生效(包含了annotation-config标签的作用)。
2、getBean的默认名称是类名(头字母小写),如果想自定义,可以@Service(“aaaaa”)这样来指定。
这种bean默认是“singleton”的,如果想改变,可以使用@Scope(“prototype”)来改变。
注入方式:
把DAO实现类注入到action的service接口(注意不要是service的实现类)中,注入时不要new 这个注入的类,因为spring会自动注入,如果手动再new的话会出现错误,然后属性加上@Autowired后不需要getter()和setter()方法,Spring也会自动注入。
posted on 2022-06-15 17:27 ExplorerMan 阅读(275) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2021-06-15 kafka消费者如何才能从头开始消费某个topic的全量数据
2021-06-15 kafka consumer消费者 offset groupID详解