使用注解开发
Maven依赖包引入
在Spring4之后,要使用注解开发,必须要保证aop的包导入了
Spring Bean配置
我们在使用注解的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持。使用注解需要导入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:content="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd"><!--指定要扫描的包,这个包下的注解就会生效--><content:component-scan base-package="com.package.name" /><content:annotation-config/></beans>
@Autowired
- 自动装配,通过类型(byType)、名字(byName)
- 如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value=”beanId”)
@Resource
- 自动装配,通过名字(byName)、类型(byType)
- 如果Resource不能唯一自动装配上属性,可以通过@Resource(name=”beanId”)
@Component
@Component有几个衍生注解,在web开发中,会按照MVC三层结构分层:
- dao【@Repository】
- service【@Service】
- controller【@Controller】
这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean。
xml与注解
- xml更加万能,适用于任何场合,维护简单方便。
- 注解不是自己类使用不了,维护相对复杂。
xml与注解最佳实践
- xml用来管理bean。
- 注解只负责完成属性的注入。
使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置了,全权交给Java来做。
JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能!
实体类
package com.kuang.pojo;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;// 使用@Component注解,就是说明这个类被Spring接管了,注册到了容器中@Componentpublic class User {private String name;public String getName() {return name;}@Value("Harry")public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +'}';}}
配置类
package com.kuang.config;import com.kuang.pojo.User;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;// 这个也会被Spring容器托管,注册到容器中,应为他本来就是一个Component// @Configuration代表这是一个配置类,就和之前的applicationContext.xml一样@Configuration@ComponentScan("com.kuang.pojo")@Import(WebConfig.class)public class AppConfig {// 注册一个Bean,就相当于之前写的一个bean标签// 这个方法的名字,就相当于bean标签中的id属性// 这个方法的返回值,就相当于bean标签中的class属性@Beanpublic User user() {return new User(); // 就是返回要注入到Bean的对象}}
测试类
import com.kuang.config.AppConfig;import com.kuang.pojo.User;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class UserTest {public static void main(String[] args) {// 如果完全使用了配置类方式去做,我们就只能通过AnnotationConfigApplicationContext上下文来获取容器,通过配置类的class对象加载。ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);User user = (User) context.getBean("user");System.out.println(user.getName());}}
这种纯Java的配置方式,在Spring boot中随处可见。
