使用注解开发
在spring4之后,要使用注解必须导入 spring-aop 的包。不过之前一直使用的 spring-webmvc 依赖已经包含了 aop 的包,就非常方便了.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
创建配置文件 applicationContext.xml,然后就是和上节一样的,在配置文件中添加注解的约束
<?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.baifu.pojo"/>
注意:如果配置了 < context : component-scan > 那么 < context : annotation-config /> 标签就可以不用再xml中配置了,因为前者包含了后者。不过为了看起来好看还是写着吧。
Bean注册@Component
使用 @Component 注解,可以将一个类交给 Spring 管理(注册为组件 Component ),即创建一个 bean 对象,默认的 id 就是类名(小写)
新建实体类 User,同时使用 @Component 注解
@Component
// 相当于 <bean id="user" class="com.baifu.pojo.User"/>
public class User {
public String name = "baifu";
}
还是按照之前的方式获取对象
public class MyTest {
@Test
public void Test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user", User.class);
System.out.println(user.name);
}
}
// 执行结果
// baifu
也可以给 @Component 设置 value,也就是 bean 的 id,如
@Component(value = "user1")
// 相当于 <bean id="user" class="com.baifu.pojo.User"/>
public class User {
public String name = "baifu";
}
这样获取对象的时候就可以通过 user1 来获取了,user 就不存在了,继续使用user会报错。
属性注入@Value
上面的 name 是预先设置好的值,那想要用注解进行属性注入该怎么办呢?
那就要使用 @Value 注解
@Component
// 相当于 <bean id="user" class="com.baifu.pojo.User"/>
public class User {
@Value("百福")
// 相当于 <property name="name" value="百福"/>
public String name;
}
注意:@Value 是用于基本类型的属性注入;如果要注入依赖(对象),用的是自动装配,如 @Resource!
@Component衍生注解
这里为了让其他包中的注解生效,还要在 applicationContext.xml 中添加
<context:component-scan base-package="com.baifu"/>
加了之后在下面添加完注解就能看到代表被 Spring 管理的小叶子了。
@Component 有几个衍生的注解,名字不同但功能相同,用在 MVC 架构的不同层。
在 Dao 层,使用 @Repository
@Repository
public class UserDao {
}
在 Service 层,使用 @Service
@Service
public class UserService {
}
在 Controller 层,使用 @Controller
@Controller
public class UserController {
}
这四个注解的功能都是一样的,都是代表将某个类注册到 Spring 中并装配!\
作用域注解@Scope
使用 @Scope 注解设置作用域,就和 bean 标签中的 scope 属性一样
Component
//@Scope("singleton")
@Scope("prototype")
public class User {
@Value("QiyuancByValue")
public String name;
}
也是之前说的 singleton 单例和 prototype 原型,两种。不显式设置当然还是单例的啦。
总结
XML 与注解两种配置方式对比
- XML:更加万能,适用于任何场合,且维护更方便,尤其是面对负责的属性如list,map,array等!
- 注解:只能在对应的类上使用,维护也比较复杂,针对比较简单的属性!
XML 与注解的最佳实践
- 用 XML 来管理 bean
- 注解只负责属性的注入
这样一来可以在 XML 中看到有哪些 bean 是给 Spring 管理了,也不用去注意其中的属性注入,是一种比较好的方式.
参考: https://blog.youkuaiyun.com/qq_43560701/article/details/119889858