使用注解开发
1. 说明
在spring4之后,想要使用注解形式,必须得要引入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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
2. Bean的实现@Component
我们之前都是使用 bean 的标签进行bean注入,但是实际开发中,我们一般都会使用注解!
- 配置扫描哪些包下的注解
<!--指定注解扫描包-->
<context:component-scan base-package="com.xxc.pojo"/>
- 在指定包下编写类,增加注解
@Component("user") // 不写括号的时候默认为类首字母小写名
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 测试
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user", User.class);
user.setName("江南");
System.out.println(user.getName());
}
}
3. 属性注入@Value(“值”)
对于上面的测试代码,我们先不执行user.setName(“江南”);而是使用注解。修改我们的实体类。
User.java
@Component("user") // 不写括号的时候默认为类首字母小写名
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
private String name;
public String getName() {
return name;
}
@Value("江南")
public void setName(String name) {
this.name = name;
}
}
注意:注解的首字母一般大写。
测试
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user", User.class);
System.out.println(user.getName());
}
}
说明:这里并没有setName();
说明:可以不用提供set方法,直接在属性名上添加@value(“值”)
如果提供了set方法,在set方法上添加@value(“值”);
4. @Component的三个衍生注解
我们这些注解,就是替代了在配置文件当中配置步骤而已!更加的方便快捷!
@Component三个衍生注解
为了更好的进行分层,Spring可以使用其它三个注解,目前使用哪一个功能都一样。
- @Controller:web层
- @Service:service层
- @Repository:dao层
以上这些注解,功能一样,就相当于将这个类交给Spring管理装配了!
我们前面写了指定注解扫描包
<context:component-scan base-package="com.xxc.pojo"/>
那如果使用了衍生注解,这些注解所在类并不完全在pojo下,这个时候,我们可以扩大指定注解扫描包的作用范围。
<context:component-scan base-package="com.xxc"/>
5. 自动装配注解
在Bean的自动装配已经讲过了。
https://blog.csdn.net/weixin_45842494/article/details/122777536
6. 作用域
@scope
- singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂,所有的对象都会销毁。
- prototype:多例模式。关闭工厂,所有的对象不会销毁。内部的垃圾回收机制会回收。
@Component("user")
@scope("prototype")
public class User {
@Value("江南")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
7. 小结
XML与注解比较
- XML可以适用任何场景 ,结构清晰,维护方便
- 注解不是自己提供的类使用不了,开发简单方便
xml与注解整合开发 :推荐最佳实践
- xml管理Bean
- 注解完成属性注入
- 使用过程中, 可以不用扫描,扫描是为了类上的注解
<context:annotation-config/>
作用:
- 进行注解驱动注册,从而使注解生效
- 用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显式的向Spring注册
- 如果不扫描包,就需要手动配置bean
- 如果不加注解驱动,则注入的值为null!