1、什么是注解
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值…)
(2)使用注解,注解作用在类上面,方法上面,属性上面·
(3)使用注解目的:简化xml配置
2、Spring针对Bean管理中创建对象提供注解
(1) @Component.
(2)@Serviceu
(3) @Controller
(4)@Repository
第一步引入依赖·
第二步开启组件扫描·
第三步创建类,在类上面添加创建对象注解
<?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">
<context:component-scan base-package="cn.zsp.spring5"></context:component-scan>
</beans>
使用到的类:
package cn.zsp.spring5.service;
import org.springframework.stereotype.Component;
@Component
public class UserService {
public void show(){
System.out.println("成功使用注解");
}
}
测试类:
public void test1(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.show();
}