Springcloud 学习笔记10-常用注解02 @Autowired,@ComponentScan,@Component,@SpringBootApplication,@EnableFeignClients,@FeignClient,@EnableDiscoveryClient,@Service,@Value

1.org.springframework包下

1.1 @Autowired

@Autowired 是一个注解,它可以对类成员变量、方法及构造函数进行标注,让 spring 完成 bean 自动装配的工作。
@Autowired 默认是按照类去匹配,配合 @Qualifier 指定按照名称去装配 bean。

使用方法:
方式一:成员属性字段使用 @Autowired,无需字段的 set 方法。直接应用于字段是我们使用的最多的一种方式

 方式二:set 方法使用 @Autowired

private ArticleService articleService;
@Autowired
public void setArticleService(ArticleService articleService) {
    this.articleService = articleService;
}

方式三:构造方法使用 @Autowired

private TagService tagService;
@Autowired
public TestController(TagService tagService) {
    this.tagService = tagService; 
}

1.2 @ComponentScan 注解

spring里有四大注解:@Service,@Repository,@Component,@Controller,这四个注解用来定义一个bean。@ComponentScan注解就是用来自动扫描被这些注解标识的类,最终生成ioc容器里的bean.可以通过设置@ComponentScan的basePackages,includeFilters,excludeFilters属性来动态确定自动扫描范围,包括的类型,以及不扫描的类型.默认情况下:它扫描所有类型,并且扫描范围是@ComponentScan注解所在配置类包及子包的类

注:所以SpringBoot的启动类最好是放在root package下,因为默认不指定basePackages。

@ComponentScan告诉Spring 哪个packages 的用注解标识的类 会被spring自动扫描并且装入bean容器。

例如,如果你有个类用@Controller注解标识了,那么,如果不加上@ComponentScan,自动扫描该controller,那么该Controller就不会被spring扫描到,更不会装入spring容器中,因此你配置的这个Controller也没有意义。

1.3 @Component

被@Component注解标识的类,会被纳入Spring容器中统一管理,好处是什么?一句话概括:你不用自己new了!

注意:若要使用spring 自动注入@Autowired,则必须添加包含@Component的注解。

1.4 @SpringBootApplication

@SpringBootApplication其实就是以下三个注解的总和。

@Configuration: 用于定义一个配置类

@EnableAutoConfiguration :Spring Boot会自动根据你jar包的依赖来自动配置项目。

@ComponentScan: 告诉Spring 哪个packages 的用注解标识的类 会被spring自动扫描并且装入bean容器。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    Class<?>[] exclude() default {};

    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};
}

 1.5 @EnableFeignClients

@EnableFeignClients:用于启用feign客户端;

package com.hztest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(FeignServiceApplication.class, args);
    }

}

1.6 @FeignClient

FeignClient注解被@Target(ElementType.TYPE)修饰,表示FeignClient注解的作用目标在接口上

通过@FeignClient(name = "服务名", path = "服务前缀")注解调用远程服务时

 "服务名" 填写 远程服务配置的: spring.application. name=服务名

 "服务前缀" 填写 远程服务配置的:server.servlet.context-path ,远程服务没有配置,path不用配置

package com.hztest.api;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

@FeignClient(name = "user-service", path = "/student")
@Component
public interface StoreService {
    @PostMapping("/getInfo")
    String getInfo();

    @PostMapping("/getId")
    String getId(@RequestParam(value="id") int id);
}

1.7 @EnableDiscoveryClient

@EnableDiscoveryClient和@EnableEurekaClient共同点就是:都是能够让注册中心能够发现,扫描到该服务。

不同点:@EnableEurekaClient只适用于Eureka作为注册中心,@EnableDiscoveryClient 可以是其他注册中心。

1.8 @Service

@Service注解用于类上,标记当前类是一个service类,加上该注解会将当前类自动注入到spring容器中,不需要再在applicationContext.xml文件定义bean了。

package com.hztest.service.impl;
import com.hztest.service.StudentService;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService {

    @Override
    public String getStudentId(int id) {
        return "user-service:"+id;
    }

    @Override
    public String getTestResult() {
        return "hello feign";
    }
}

在调用该service的时候只需要将该类注入接口中即可:

1.9 @AliasFor

@AliasFor 表示别名,它可以注解到自定义注解的两个属性上,表示这两个互为别名,也就是说这两个属性其实同一个含义。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Inherited
public @interface MyAnnotation {
    @AliasFor(attribute = "location")
    String value() default "";
    
    @AliasFor(attribute = "value")
    String location() default "";
}

1.10 @Value

@Value的作用是通过注解将常量、配置文件中的值、其他bean的属性值注入到变量中,作为变量的初始值。

<1>常量注入

    @Value("normal")
    private String normal; // 注入普通字符串

    @Value("classpath:com/hry/spring/configinject/config.txt")
    private Resource resourceFile; // 注入文件资源

    @Value("http://www.baidu.com")
    private Resource testUrl; // 注入URL资源

<2>配置文件属性注入@Value("${}")

@Value("${}")读取配置文件中的值,注入到变量中去。配置文件分为默认配置文件application.properties和自定义配置文件

application.properties。application.properties在spring boot启动时默认加载此文件

package com.ttbank.flep.file.env;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "flep")
@Data
public class FileUAProperties {
    @Value("${flep.cluster_name}")
    private String clusterName;
    @Value("${flep.subsys_name}")
    private String subsysCode;
}

对应读取application.yml文件中

1.11 @ConfigurationProperties

spring-boot 提供该注解将配置文件的值映射到类上使用。

例子:
1,这是我们在application.yml配置的druid连接池学习

通过@ConfigurationProperties注解则会将值映射到该类中

注意:

(1) @ConfigurationProperties 和 @value 有着相同的功能,但是 @ConfigurationProperties的写法更为方便。

(2) @ConfigurationProperties 的 POJO类的命名比较严格,因为它必须和prefix的后缀名要一致, 不然值会绑定不上, 特殊的后缀名是“driver-class-name”这种带横杠的情况,在POJO里面的命名规则是 下划线转驼峰 就可以绑定成功。

1.12 @ConfigurationProperties注解和@Value注解的区别

都是读取配置文件属性

(1) @ConfigurationProperties(prefix = "person")读取多个属性

@Component
@ConfigurationProperties(prefix = "person")
@Data
public class Person {
    String LastName;
    int age;
    boolean boss;
    Date birth;
    Map<String, String> maps;
    List<String> list;
    Dog dog;
}

prefix = "person" 读取前缀为person的属性的值.
yaml文件对应的属性值:

person:
  LastName: 飞
  age: 12
  boss: true
  birth: 2019/6/15
  maps: {key1:value1,key2:value2}
  list: [1,2,3,4,5]
  dog:
    name: 旺财
    age: ${random.int[20]}

注意:@ConfigurationProperties和@Component配合使用;

(2) @value读取单个属性

@Component
public class Person1 {
    @Value("${person.last-name}")
    String LastName;
    //@Value("${person.age}")   @Value("#{12*2}")
    int age;
    @Value("${person.boss}")
    boolean boss;
    @Value("${person.birth}")
    Date birth;

    Map<String, String> maps;
    @Value("${person.list}")
    List<String> list;

    Dog dog;
}

注意事项:maps 和dog 不能使用@value注解,@Value不支持复杂类型

两者获取值的比较(都能从properties和yaml获值)

1.13 @Configuration、@ConfigurationProperties、@EnableConfigurationProperties

1.13.1 @Configuration

@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

  • @Configuration配置spring并启动spring容器
  • @Configuration启动容器+@Bean注册Bean
  • @Configuration启动容器+@Component注册Bean

使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法
配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext)

1.13.2 @Component和@Bean注解

(1)@Component

@Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。

注意:如果一个类添加了@Component注解,则这个类可以使用@Autowired注解注入;

@Bean注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。通常方法体中包含了最终产生bean实例的逻辑。

两者的目的是一样的,都是注册bean到Spring容器中。

1.13.3 @ConfigurationProperties

有时候有这样子的情景,我们想把配置文件的信息,读取并自动封装成实体类,这样子,我们在代码里面使用就轻松方便多了,这时候,我们就可以使用@ConfigurationProperties,它可以把同类的配置信息自动封装成实体类。

1.13.4 @EnableConfigurationProperties

@EnableConfigurationProperties注解的作用是:让使用 @ConfigurationProperties 注解的类生效。

如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。

2.lombok.*包下

(1)@Data
使用这个注解,就不用再去手写Getter,Setter,equals,canEqual,hasCode,toString等方法了,注解后在编译时会自动加进去。
(2)@AllArgsConstructor
使用后添加一个构造函数,该构造函数含有所有已声明字段属性参数
(3)@NoArgsConstructor
使用后创建一个无参构造函数
(4)@Builder
关于Builder较为复杂一些,Builder的作用之一是为了解决在某个类有很多构造函数的情况,也省去写很多构造函数的麻烦,在设计模式中的思想是:用一个内部类去实例化一个对象,避免一个类出现过多构造函数。

(5)@Slf4j

如果不想每次都写private  static Logger logger = LoggerFactory.getLogger(当前类名.class); 可以用注解@Slf4j;

示例:protected static final Logger logger = LoggerFactory.getLogger(XYZ.class);

logger.debug("hello world");
输出:XYZ:hello world

 3.org.mybatis包下

(1) @MapperScan

作用:指定要生成实现类的接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类
添加位置:是在Springboot启动类上面添加

package com.ttbank.flep.file;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableAsync;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication(scanBasePackages="com.ttbank")
@EnableFeignClients
@EnableDiscoveryClient
@EnableSwagger2
@EnableAsync
@MapperScan("com.ttbank.flep.file.mapper")
public class FileApplication {
    public static void main(String[] args) {
        SpringApplication.run(FileApplication.class,args);
    }
}

添加@MapperScan(“com.ttbank.flep.file.mapper”)注解以后,com.ttbank.flep.file.mapper包下面的接口类,在编译之后都会生成相应的实现类

使用@MapperScan注解多个包

@SpringBootApplication  
@MapperScan({"com.kfit.demo","com.kfit.user"})  
public class App {  
    public static void main(String[] args) {  
       SpringApplication.run(App.class, args);  
    }  
}  

 

参考文献:https://blog.csdn.net/nba_linshuhao/article/details/82783454

https://www.cnblogs.com/bclshuai/p/10309119.html

posted @ 2021-08-24 19:56  雨后观山色  阅读(1402)  评论(0编辑  收藏  举报