【Spring】Spring5 常见的注解和使用【二】赋值组件

【Spring】Spring5 常见的注解和使用【二】赋值组件

Alan 688 2021-03-15
@Service

用于标注业务层组件

@Controller

用于标注控制层组件。

@Repository

用于标注数据访问组件,即DAO组件。

@Component

泛指组件,当组件不好归类的时候,可以使用这个注解进行标注。上面的@Service,@Controller,@Repository注解其实等价于@Component注解,通过源码可以看到service注解其实就是在接口上加上了@Component注解,且没有其他的操作。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}
@Value

普通类型赋值,这个很好理解,在类的属性上加上这个注解,就可以给它赋值。

这里新建Bird类,然后使用注解。

@Data
@Component
public class Bird {

    @Value("鹦鹉")
    private String name;

    @Value("2")
    private int age;
}
public class MyTest {

    @Test
    public void test() {
        ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class);
        Object person = app.getBean("bird");
        System.out.println(person);
    }
}

运行测试方法,可以看到给Bird这个类赋予了默认的值。

@PropertySource

读取配置文件赋值。

在resource中添加values.properties配置文件,里面加上配置

bird.color = black

在Bird类中新增color属性,并添@PropertySource注解,使用这个配置

@Data
@Component
public class Bird {

    @Value("鹦鹉")
    private String name;

    @Value("2")
    private int age;

    @Value("${bird.color}")
    private String color;
}

在MyConfig类上加上@PropertySource注解。

@Configuration
@ComponentScan("com.alan.project.entity")
@PropertySource("classpath:values.properties")
public class MyConfig {

}

再次运行测试方法可以看见已经读取到配置。

除了使用@PropertySource注解能够读取到配置内容外,还可以使用Environment这个类

	@Test
    public void test() {
        ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class);
        Object person = app.getBean("bird");
        System.out.println(person);

        Environment environment = app.getEnvironment();
        System.out.println("从环境中读到的配置" + environment.getProperty("bird.color"));
    }

运行可以看到已经读取到配置。

@Autowired

默认按类型装配,如果我们想要按照名字装配,可以结合@Qualifier注解一起使用,当注解上同时存在@Autowired和@Qualifier两个注解的时候,优先生效的是@Qualifier注解。

@Primary

自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常。

@Resource

默认按名称装配,当找不到与名称匹配的bean才会按类型装配。


# Spring