使用注解开发
我们之前的项目都是通过手动配置bean,通过spring的配置文件来注入的,上一篇Blog我们学到了使用注解进行自动装配,注解的出现使我们所需要编写的代码更加的简单,容易。因此,注解开发出现了~
【注意:想要使用注解形式,必须得要引入aop的包
】
注解开发:
- 在配置文件当中,还得要引入一个context约束和开启属性注解支持
- 在配置文件中,配置扫描哪些包下的注解
<context:component-scan base-package="pojo"/>
,扫描pojo下的注解
<?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="pojo"/>
</beans>
- 在你要配置的包下写注解
package pojo;
import org.springframework.stereotype.Component;
@Component("user")
public class User {
private String name = "xiaomi";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Component("user") 相当于配置文件中
<bean id="user" class="pojo.User"/>
- 属性注入(两种方法)
- 直接在属性在加
@Value()
注解- 在set方法上加
@Value()
注解
package pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("user") //相当于配置文件中 <bean id="user" class="pojo.User"/>
public class User {
@Value("xiaohong")
private String name;
public String getName() {
return name;
}
//@Value("xiaoming")
public void setName(String name) {
this.name = name;
}
}
思考一下,如果两个地方都加了@Value
注解,取谁的值呢?
取
set
方法上的!!!
@Component三个衍生注解
- @Controller:web层
- @Service:service层
- @Repository:dao层 ====>这四个注解的功能差不多,只是适用的层面不一样而已。
@scope 作用域
- singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
- prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
@Scope("prototype")
public class User {
@Value("小红")
public String name;
}
小结: XML与注解比较
- XML可以适用任何场景 ,结构清晰,维护方便
- 注解不是自己提供的类使用不了,开发简单方便 xml与注解整合开发 【推荐最佳实践】
- xml管理Bean
- 注解完成属性注入
- 使用过程中,可以不用扫描,扫描是为了类上的注解