1. 什么是注解
- 注解是代码总特殊的标记,格式:@注解名称(属性名称=属性值)
- 使用注解,注解作用在类上面,方法上面,属性上面
- 使用注解目的:简化xml配置
2. Spring 针对 Bean 管理中创建对象提供注解
- @Component
- @Service
- @Controller
- @Repository
* 上面的四个注解功能是一样的,都可以用来创建Bean实例
3. 基于注解方式实现对象的创建
- 引入依赖,引入aop的依赖
- 开启组件的扫描
<?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
">
<!-- 开启组件扫描 -->
<!-- 1. 如果扫描多个包,使用逗号隔开-->
<!-- 2. 扫描包的上层目录-->
<context:component-scan base-package="com.study.modules.annotate" ></context:component-scan>
</beans>
package com.study.modules.annotate.service;
import org.springframework.stereotype.Component;
/**
* 在注解里面 value 属性值可以省略不写
* 默认值是类名称,首字母小写.
*/
@Component(value = "userService")
public class UserService {
public void add() {
System.out.println("service add ……");
}
}