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

1.org.springframework包下

(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; 
}

(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也没有意义。

(3)@Component

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

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

(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 {};
}

 (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);
    }

}

(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);
}

(7)@EnableDiscoveryClient

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

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

(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的时候只需要将该类注入接口中即可:

(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 "";
}

(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文件中

(11)@ConfigurationProperties

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

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

通过@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

原文地址:https://www.cnblogs.com/luckyplj/p/15181927.html