Spring中的特殊注解:
@Component : 用于标注实体类
@Repository :用于标注DAO类
@Service : 用于标注业务类
@Controller : 用于标注控制器类
举例如下:(和数据库打交道的全部省略,只实现了业务逻辑)
1、导入相关jar包(除了那5个核心jar包外,使用注解需要导入aop包)
2、编写配置文件(使用注解需要在配置文件中开启扫描注解)
<?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-4.0.xsd">
<!-- 扫描包中使用注解的类 -->
<context:component-scan base-package="com.xyj.dao,com.xyj.service,com.xyj.entity"></context:component-scan>
</beans>
开启扫描注解时多个包使用逗号分隔,或者可以:
<context:component-scan base-package="com.xyj"></context:component-scan>
开启扫描后,如果在某个类中使用了相关注解,该类右上角会有一个“ S ”的绿色标记。
3、编写实体类:
实体类上使用@Component注解,值使用@Value
package com.xyj.entity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("user")
public class User {
@Value