9、使用注解开发
在spring4之后,想要使用注解形式,必须得要引入aop的包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
我们现在使用的是Spring5,只用导入上面一个依赖,就导入了下面这些jar包
在配置文件当中,还得要引入一个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
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:annotation-config/>
<!--指定注解扫描包-->
<context:component-scan base-package="cn.edu.cxtc.pojo"/>
</beans>
1、bean的注入
我们之前都是使用bean的标签对JavaBean(bean)进行注入,但是在实际开发中, 我们一般都会使用注解进行开发
使用xml配置文件进行bean的实现
<bean id="people" class="cn.edu.cxtc.pojo.People">
</bean>
- 配置扫描哪些包下的注解
<!--指定注解扫描包-->
<!--他会扫描cxtc包下,所有的类,包含pojo,service层,dao层..-->
<context:component-scan base-package="cn.edu.cxtc"/>
- 在指定包下编写类,增加注解
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
private String name;
private int age;
getter() setter() 和toString()方法
}
-
注意:@Component(“id”):在JavaBean(pojo) 类上面加这个注释,就相当于在xml文件中注册了一个bean,创建处对象(无参构造)。
但是,我们这里只是注册了一个JavaBean,但是还没有为里面的属性赋值,
-
测试
@Test
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user", User.class);
System.out.println(user.getName()); //name = null
}
2、属性注入
使用注解注入属性
- 可以不用提供set方法,直接在直接名上添加@value(“值”)
package cn.edu.cxtc.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("student")
public class Student {
@Value("张皓程")
private String name;
@Value("21")
private int age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
- 如果提供了set方法,在set方法上添加@value(“值”);
@Value("张皓程")
public void setName(String name) {
this.name = name;
}
3、衍生注解
我们的这些衍生注解,就是替代了在配置文件当中配置步骤而已!更加的方便快捷!其实都是向xml配置文件中注册bean!
3.1、@Component三个衍生注解
为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。
- @Controller:web层
- @Service:service层
- @Repository:dao层
写上这些注解,就相当于将这个类交给Spring管理装配了!
3.2、bean的自动装配注解
在前面的bean的自动装配中已经讲过了,回顾一下
@Autowired
@Qualifier
@Resource
3.3、作用域
@scope
- singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
- prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
@Controller("user")
@Scope("prototype")
public class User {
@Value("秦疆")
public String name;
}
4、小结
XML与注解比较
- XML可以适用任何场景 ,结构清晰,维护方便
- 注解不是自己提供的类使用不了,开发简单方便
xml与注解整合开发 :推荐最佳实践
- xml管理Bean
- 注解完成属性注入
- 使用过程中, 可以不用扫描,扫描是为了类上的注解
<context:annotation-config/>
作用:
- 进行注解驱动注册,从而使注解生效
- 用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显示的向Spring注册
- 如果不扫描包,就需要手动配置bean
- 如果不加注解驱动,则注入的值为null!