Spring初级:使用注解开发

77 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第33天,点击查看活动详

注解配置

component-scan

使用<context:component-scan base-package=””/>启用组件扫描。框架会自动给容器中注册带有以下注解的Bean。

  • @Component  通用组件,任何类都可以用此注解

  • @Controller  表示层控制器组件

  • @Service   业务层组件

  • @Repository  数据访问层组件

  • @Scope(“singleton”)  配置bean的作用域

annotation-config

使用context:annotation-config/启用属性或方法的注解配置,激活已经配置到容器的bean。如果同时使用context:component-scan/和当前注解context:annotation-config/会被忽略。

  • @PostConstruct  配置在初始化方法。Java EE提供的注解,需web环境。

  • @PreDestroy  配置在销毁方法。Java EE提供的注解,需web环境。

  • @Autowired  可用在成员变量或set方法上,根据类型自动注入。

    如果容器中有多个相同类型的bean,可配合使用@Qualifier(“beanId”)使用。

  • @Resource  可用在变量和set方法上,将根据名称自动注入。

@Value注解

  • 给属性注入简单类型。例:@Value(“tom”)

  •  读取properties属性文件的值注入给bean的属性:

    在配置文件中配置PropertySourcesPlaceholderConfigurer,且给locations属性注入属性文件的路径

    @Value("${key}")

    说明:PropertySourcesPlaceholderConfigurer就是context:property-placeholder的底层实现。

annotation-driven

使用<tx:annotation-driven transaction-manager ="" />启用注解方式的事务控制。需要先配置事务管理器DataSourceTransactionManager,事务管理器又需要数据源。

  • 在业务层类或方法上使用@Transactional注解。

例:@Transactional(propagation=Propagation.REQUIRED,readOnly=true)

如果加在类上,则所有方法都被织入事务advice;如果加在方法上,则该方法将被织入事务advice,没有标注@Transactional的方法不会有事务。

自定义切面类相关注解(了解)

  • 切面类用@Aspect(value)进行注解

  • 切面类中通知方法的注解有

    @Before("execution(* *.*(..))")

    @AfterReturning(pointcut = "",returning = "")

    @AfterThrowing(pointcut = "",throwing = "")

    @After("")

    @Around("")

如何使用注解

在Spring4之后,要使用注解开发,必须保证aop包导入

image.png

使用注解需要导入 context:annotation-config/ 约束,增加支持!

<?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>

属性如何注入

@Component
public class User {
    //相当于 <property name="name" value="李四" />

    public String name;

    @Value("李四")
    public void setName(String name) {
        this.name = name;
    }
}

自动装配

- @Autowired:自动装配,通过类型,名字,如果@Autowired不能唯一的自动装配上属性,则需要通过@Qualifier(value = "xxx")
- @Nullable 字段标记了这个注解,说明字段可以为null
- @Resource:自动装配通过类型,名字
- @Component组件放在类上,说明这个类被Spring管理,就是bean!

作用域

@Component
@Scope("singleton")
public class User {
    //相当于 <property name="name" value="李四" />

    public String name;

    @Value("李四")
    public void setName(String name) {
        this.name = name;
    }
}

小结:

xml与注解:

  • xml更加万能,适用于任何场合,维护方便
  • 注解不是自己类使用不了,维护相对复杂。

xml与注解最佳实践:

  • xml用来管理bean
  • 注解只负责完成属性的注入。
  • 在使用过程中需要注意,必须让注解生效,需要开启注解的支持
    <!-- 指定要扫描的包,这个包下的注解会生效-->
    <context:component-scan base-package="com.zhao" />

    <context:annotation-config/>

使用java的方式配置Spring

创建实体类

@Component
public class User {

    private String name;

    public String getName() {
        return name;
    }
    //注入值
    @Value("李四")
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

配置类

 package com.zhao.config;
 ​
 import com.zhao.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容器托管,注册到容器中
 @Configuration //代表是一个配置类,例如之前的beans.xml
 @ComponentScan("com.zhao.pojo")
 @Import(ZhaoConfig2.class)
 public class ZhaoConfig {
 ​
     //注册bean相当于之前写的bean
     //这个方法的名字相当于bean中的id
     //方法的返回值代表bean中的class属性
     @Bean
     public User getUser(){
         return new User();//返回注入bean的对象
     }
 }
 ​

测试类

public class MyTest {

    public static void main(String[] args) {
        //如果完全使用配置类的方法做,我们就只能通过ApplicationContext上下文获取容器,通过配置类class加载
        ApplicationContext context=new AnnotationConfigApplicationContext(ZhaoConfig.class);
        User user=(User) context.getBean("getUser");
        System.out.println(user.getName());
    }
}

image.png