Spring注解开发
Spring注解开发,仍然不是零配置
在Spring 4之后,要使用注解开发,必须导入aop的包。
使用注解需要导入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:component-scan base-package="com.shang.pojo"/>
<context:annotation-config/><!--有上面包扫描,此行可省略-->
</beans>
- 怎么将Bean加入到容器
@Component
@Component
public class People {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
'}';
}
}
- 属性如何注入?
@Value
@Component
public class People {
@Value("shang") //<property name="name" value="shang"></property>
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
'}';
}
}
- 衍生的注解
@Component
有三个衍生注解,我们在web开发中,会按照mvc三层架构分层!
@Controller
、@Service
、@Repository
这四个注解都表示将当前类加入到容器中,也就是装配Bean - 自动装配
前面有介绍 - 作用域
@Scope
在SpringBoot开发中,我们会使用大量注解,我们要知道哪些注解是Spring的,哪些注解是SpringBoot特有的,到时候千万不要说你不知道!