前言
前文介绍了在.xml文件中开发的方法。相对与注解来讲,xml更加使用于任何场合,维护起来更加方便。本文介绍的注解开发,不是自己的类使用不了,维护起来相对麻烦。但是,可将xml开发和注解开发搭配使用,xml管理bean,注解负责完成属性的注入即可。
一、导入包
导入依赖spring-webmvc,确定其中的aop包已导入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.2</version>
</dependency>
二、导入约束,开启注解支持
在.xml文件中导入
- 1.需要扫描的包
<context:component-scan base-package="包名"></context:component-scan>
- 2.注解驱动约束
<context:annotation-config/>
- 示例:
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 指定要扫描的包,这个包下的注解就会生效 -->
<context:component-scan base-package="包名"></context:component-scan>
<!-- 注解驱动 -->
<context:annotation-config/>
</beans>
三、 添加注解
1. 添加方法
@Component:该注解放在需管理的实体类前,说明该类被Spring管理,相当于创建了一个bean,功能等同下方代码。
<bean id="xxx" class="xxx">
@Value(“属性值”):该注解放在属性名前或者该属性set方法前,用于属性值的注入,功能等同下方代码。
<property name="xxx" value="xxx">
2. 代码示例
- 目的:向实体类User的对象传入属性username传入属性值
- 创建实体类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
@Value("yumi")
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
- 测试
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user", User.class);
System.out.println(user.getUsername());
}
}
四、衍生注解
@Repository、@Service、@Controller分别用于javaweb开发中的dao层、service层、controller层。该注解功能与@Component一致。