使用注解开发Spring
首先需要完成一些准备工作
- 环境搭建
- 在pom.xml中添加依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
- applicationContext.xml中配置加入context约束,增加对注解的支持
<?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:annotation-config/>
</beans>
之后是一些配置
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.qcp.pojo"/>
正式进入注解
-
@Component
component英文是组件的意思,在上文中的component-scan扫描包之后,即可在类中使用此注解,放在类上,说明该类被Spring管理,就是bean
@Component
public class User {
public String name = "qcp";
}
↑ 等价于 ↓
<bean id="user" class="com.qcp.pojo.User"></bean>
-
@Value
可以放在需要注入值的属性上,也可以放在set方法上,适用于简单形式的值注入,复杂情况建议直接使用配置文件注入值
@Component
public class User {
@Value("qcp")
public String name;
}
↑ 等价于 ↓
<bean id="user" class="com.qcp.pojo.User">
<property name="name" value="qcp"></property>
</bean>
- 衍生注解
@Component有几个衍生注解,在web开发中,会按照MVC三层架构分层!
- dao 【@Repository】在dao层中一般使用@Repository来代替@Component,功能一样
- service 【@Service】在service层中一般使用@Service来代替@Component,功能一样
- controller 【@Controller】在controller层中一般使用@Service来代替@Controller,功能一样
- 这四个注解功能都是一样的,都是将某个类注册到Spring中,装配bean
- 总结applicationContext.xml与注解:
- xml更加万能,适用于任何场合,维护简单方便
- 注解不是自己的类使用不了,维护相对复杂
xml与注解的最佳实践:
xml用来管理bean
注解只负责属性的注入
自动装配的注解
@Autowired 和 @Resource
- 都是用来自动装配的,都放在字段属性上
- @Autowired 通过byType方式实现,要求这个对象必须存在!
- @Resource 默认通过byName方式,如果找不到名字,则会使用byType方式。
注解+纯Java实现Spring配置
User.java
//这个注解说明该类被Spring托管,注册到了容器中
@Component
public class User {
//给属性注入值
@Value("qcp")
private String name;
public User() {
}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
config.java
@Configuration
public class config {
@Bean
public User getUser(){
return new User();
}
}
测试类
public class MyTest {
@Test
public void test1(){
ApplicationContext context = new AnnotationConfigApplicationContext(config.class);
User user = (User) context.getBean("getUser");
System.out.println(user.getName());
}
}