
@Builder
@Builder
@Data
public class DoctorVO {
    private String name;
    private String address;
    private Integer age;
}
public class DoctorTest {
    public static void main(String[] args) {
        DoctorVO doctorVO = DoctorVO.builder()
                .name("LH")
                .address("北京")
                .age(11)
                .build();
        System.out.println("name: " + doctorVO.getName());
        System.out.println("address: " + doctorVO.getAddress());
        System.out.println("age: " + doctorVO.getAge());
    }
}
输出:
name: LH
address: 北京
age: 11
@ConditionalOnClass
是Springboot实现自动配置的重要支撑之一。其用途是判断当前classpath下是否存在指定类,若是则将当前的配置装载入spring容器。
@ConditionalOnBean         //    当给定的在bean存在时,则实例化当前Bean
@ConditionalOnMissingBean  //    当给定的在bean不存在时,则实例化当前Bean
@ConditionalOnClass        //    当给定的类名在类路径上存在,则实例化当前Bean
@ConditionalOnMissingClass //    当给定的类名在类路径上不存在,则实例化当前Bean
例子:
@Configuration
@ConditionalOnClass(RestHighLevelClient.class)
@Slf4j
public class EsConfig {
    @Bean
    RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(lowLevelRestClient);
        return client;
    }
}
@PreDestroy
被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。
PreDestroy 注释作为回调通知用于各方法,以表示该实例正处于被容器移除的过程中。用 PreDestroy 注释的方法通常用于释放它已持有的资源。
@PostConstruct
@PostConstruct注解好多人以为是Spring提供的,其实是Java自己的注解。@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:
Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
@PostConstruct
public void someMethod(){}
或者
public @PostConstruct void someMethod(){}
@JsonFormat
完成格式转换。例如对于Date类型字段,如果不适用JsonFormat默认在rest返回的是long,如果我们使用@JsonFormat(timezone = “GMT+8”, pattern = “yyyy-MM-dd HH:mm:ss”),就返回"2018-11-16 22:58:15"
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date regDate;
@JsonIgnoreProperties
解决范围:开发中有使用过实体数据拷贝问题,两个实体之间属性值数量可能不一样多,所以会存在拷贝失败问题,开发中有使用过实体数据拷贝问题,两个实体之间属性值数量可能一样多,所以会存在拷贝失败问题。
@JsonIgnoreProperties(ignoreUnknown = true)
public static class MsgBody {
   private String type;
   /**
    * 文本消息 "type": "HIMText"
    */
   private String text;
}
补充:将这个注解写在类上之后,指定的字段不会被序列化和反序列化。
@JsonIgnoreProperties({ "字段名称1", "字段名称2" })
@Component
作用及范围:把对象加载到Spring容器中,最基础的存在,很多的注解都是继承它的,只有一个属性值,默认值是“”。
源码:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
    String value() default "";
}
@Service
作用及范围:一般用于Service层的注解,继承了Component组件,本质上一样,方便做业务范围区分而已。
源码:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
    @AliasFor(annotation = Component.class)
    String value() default "";
}
@Repository
作用及范围:作用于Dao层的注解,很多经常用JPA的同学都清楚这个东西,与Service本质上一样,业务领域上区别而已。
源码:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
    @AliasFor(annotation = Component.class)
    String value() default "";
}
@Controller
作用及范围:作用在控制器上的注解,与Service一样,业务领域区分。
源码:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
    @AliasFor(annotation = Component.class)
    String value() default "";
}
@Autowired
作用及范围:它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作,其实就是获取容器中的对象。
注意事项:在使用@Autowired时,首先在容器中查询对应类型的bean
- 如果查询结果刚好为一个,就将该bean装配给@Autowired指定的数据
- 如果查询的结果不止一个,那么@Autowired会根据名称来查找。
- 如果查询的结果为空,那么会抛出异常。解决方法时,使用required=false
源码:
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    boolean required() default true;
}
@Resource
作用及范围:它是JSR250规范的实现,也是需要导入javax.annotation实现注入,根据名称进行自动装配的,一般会指定一个name属性,可以作用在变量、setter方法上。
源码:
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Repeatable(Resources.class)
public @interface Resource {
    String name() default "";
  
    String lookup() default "";
    Class<?> type() default java.lang.Object.class;
    enum AuthenticationType {
        CONTAINER,
        APPLICATION
    }
    AuthenticationType authenticationType() default AuthenticationType.CONTAINER;
    boolean shareable() default true;
    String mappedName() default "";
    String description() default "";
}
@Inject
作用及范围:它是JSR330 (Dependency Injection for Java)中的规范,需要导入javax.inject.Inject;实现注入,根据类型进行自动装配的,如果需要按名称进行装配,则需要配合@Named,可以作用在变量、setter方法、构造函数上。很少用。
例子:
@Inject
public Message(Header header, Content content)
{
    this.headr = header;
    this.content = content;
}
public class Messager
{
    @Inject
    private Message message;
}
@Configuration
作用及范围:从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,同样AliasFor最原始的注解Component
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    @AliasFor(annotation = Component.class)
    String value() default "";
    boolean proxyBeanMethods() default true;
}
@Bean
作用及范围:作用于方法上,产生一个对象,然后这个对象交给Spring管理,在进行初始化的过程中,只会产生并调用一次,如果容器管理一个或者多个bean,这些bean都需要在Configuration注解下进行创建,在一个方法上使用Bean注解就表明这个方法需要交给Spring进行管理。
源码:
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
    @AliasFor("name")
    String[] value() default {};
    @AliasFor("value")
    String[] name() default {};
    Autowire autowire() default Autowire.NO;
    String initMethod() default "";
    String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
}
@ComponentScan
作用及范围:扫描当前类下面的所有对象,为什么说Component是最基础的东西,就是要给这个注解扫描,非常巧妙的设计,可以扫描多个包。
例子:
@ComponentScan(“com.abc.aaa”)
@SpringBootApplication
public class SpringbootApplication {}
@ComponentScan({"com.abc.bbb","com.abc.aaa"})
@SpringBootApplication
public class SpringbootApplication {}
@WishlyConfiguration
作用及范围:这个是Configuration与ComponentScan的组合注解,可以替代这两个注解,目前非常少用。
@Aspect
作用及范围:切面注解,切面编程经常用到的,可以做日志
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Aspect {
    public String value() default "";
}
@After
作用及范围:配置Aspect做切面使用,在方法执行之后执行(方法上)
源码:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface After {
    String value();
    
    String argNames() default "";
}
@Before
作用及范围:配置Aspect做切面使用,在方法执行之前执行(方法上)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Before {
    String value();
    
    String argNames() default "";
}
@Around
作用及范围:配置Aspect做切面使用,在方法执行之前与之后执行(方法上)
源码:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Around {
    String value();
    
    String argNames() default "";
}
@PointCut
作用及范围:配置Aspect做切面使用,声明切点
源码:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Pointcut {
  
    String value() default "";
    
    String argNames() default "";
}
@Scope
作用及范围:
- Singleton (单例,一个Spring容器中只有一个bean实例,默认模式), 
- Protetype (每次调用新建一个bean), 
- Request (web项目中,给每个http request新建一个bean), 
- Session (web项目中,给每个http session新建一个bean), 
- GlobalSession(给每一个 global http session新建一个Bean实例) - 源码: @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Scope { - @AliasFor("scopeName") String value() default ""; @AliasFor("value") String scopeName() default ""; ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;- } 
@Value
作用及范围:将外部的值动态注入到Bean中,使用的情况有:
- 注入普通字符串 
- 注入操作系统属性 
- 注入表达式结果 
- 注入其他Bean属性:注入beanInject对象的属性another 
- 注入文件资源 
- 注入URL资源 - 例子: @Value("normal") private String normal; // 注入普通字符串 - @Value("#{systemProperties['os.name']}") private String systemPropertiesName; // 注入操作系统属性 - @Value("#{ T(java.lang.Math).random() * 100.0 }") private double randomNumber; //注入表达式结果 - @Value("#{beanInject.another}") private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面 - @Value("classpath:com/hry/spring/configinject/config.txt") private Resource resourceFile; // 注入文件资源 - @Value("http://www.baidu.com") private Resource testUrl; // 注入URL资源 
@PropertySource
作用及范围:加载指定的配置文件
源码:
@PropertySource(value = {"classpath:test.properties"})
@Component
@ConfigurationProperties(prefix = "test")
public class Test {
    private Integer id;
    private String lastName;
}
@Profile
作用及范围:根据不同环境加载bean对象
例子:
@PropertySource("classpath:/user.properties")
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware{
    
    @Profile("test")
    @Bean("testUser")
    public User testUser()  {
        User a =new User();
    return a;
    }
    
    @Profile("dev")
    @Bean("devUser")
    public User devUser()  {
        User a =new User();
    return a;
    }
 
}
@Conditional
作用及范围:是Spring4新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册bean
例子:
@Configuration
public class BeanConfig {
 
    //只有一个类时,大括号可以省略
    //如果WindowsCondition的实现方法返回true,则注入这个bean    
    @Conditional({WindowsCondition.class})
    @Bean(name = "bill")
    public Window window(){
        return new Window();
    }
 
    //如果LinuxCondition的实现方法返回true,则注入这个bean
    @Conditional({LinuxCondition.class})
    @Bean("linux")
    public Linex linux(){
        return new Linex();
    }
}
@EnableAsync
作用及范围:启动异步,与Async配合使用
源码:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AsyncConfigurationSelector.class)
public @interface EnableAsync {
    Class<? extends Annotation> annotation() default Annotation.class;
    boolean proxyTargetClass() default false;
    AdviceMode mode() default AdviceMode.PROXY;
    int order() default Ordered.LOWEST_PRECEDENCE;
}
@Async
作用及范围:异步注解,需配合EnableAsync使用,使用后,方法变成异步方法
例子:
@Component
public class TreadTasks {
    @Async
    public void startMyTreadTask() {
        System.out.println("this is my async task");
    }
}
@EnableScheduling
作用及范围:定时任务注解扫描器,会扫描包体下的所有定时任务
例子:
@SpringBootApplication
@EnableScheduling //开启定时任务
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}
@Scheduled
作用及范围:定时任务控制器
@Scheduled(cron = "0 0 2 * * ?") 
@EnableJpaRepositories
作用及范围:开启对SpringData JPA Repository的支持
例子:
@EnableJpaRepositories({"com.cshtong.sample.repository", "com.cshtong.tower.repository"})
@EnableTransactionManagement
作用及范围:开启注解式事务的支持
例子:
@EnableTransactionManagement // 启注解事务管理
@SpringBootApplication
public class ProfiledemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(ProfiledemoApplication.class, args);
    }
}
@EnableCaching
作用及范围:开启注解式的缓存支持
例子:
@Configuration
@EnableCaching
public class CachingConfig {
    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("sampleCache")));
        return cacheManager;
    }
}
@Cacheable
作用及范围:把信息放到存储中去
例子:
@Cacheable(value ={"sampleCache","sampleCache2"},key="targetClass.getName()+'.'+methodName+'.'+#id")
public String getUser(int id) {
   if (id == 1) {
      return "1";
   } else {
      return "2";
   }
}
@RequestMapping
作用及范围:注解来将请求URL映射到整个类上,或某个特定的方法上
源码:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
    String name() default "";
    @AliasFor("path")
    String[] value() default {};
    @AliasFor("value")
    String[] path() default {};
    RequestMethod[] method() default {};
    String[] params() default {};
    String[] headers() default {};
    String[] consumes() default {};
    String[] produces() default {};
}
@ResponseBody
作用及范围:将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据
源码:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ResponseBody {
}
@RequestBody
作用及范围:用来接收前端传递给后端的json字符串中的数据(请求体中的数据的)
源码:
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody {
    /**
     * 默认是必须的
     */
    boolean required() default true;
}
@RequestParam
例子:
http://localhost:8080/springmvc/hello/101?param1=10¶m2=20
根据上面的这个URL,你可以用这样的方式来进行获取
public String getDetails(
    @RequestParam(value="param1", required=true) String param1,
        @RequestParam(value="param2", required=false) String param2){
...
}
@RequestParam 支持下面四种参数
defaultValue 如果本次请求没有携带这个参数,或者参数为空,那么就会启用默认值
name 绑定本次参数的名称,要跟URL上面的一样
required 这个参数是不是必须的
value 跟name一样的作用,是name属性的一个别名
@RequestParam和@PathVariable注解是用于从request中接收请求的,两个都可以接收参数,关键点不同的是@RequestParam是从request里面拿取值,而@PathVariable是从一个URI模板里面来填充
@PathVariable
作用及范围:接收请求路径中占位符的值
例子:
@RequestMapping(value=”user/{id}/{name}”)
请求路径:http://localhost:8080/user//1/james
http://localhost:8080/springmvc/hello/101?param1=10¶m2=20
上面的一个url你可以这样写:
@RequestMapping("/hello/{id}")
public String getDetails(@PathVariable(value="id") String id,
                         @RequestParam(value="param1", required=true) String param1,
                         @RequestParam(value="param2", required=false) String param2){
         .......
}
URL:http:localhost:9405/client/add/account/123456
@PostMapping(value = "/client/add/{entity}/{entityId}")
public String add(@PathVariable("entity") String entity,
                  @PathVariable("entityId") String entityId);
@RequestParam和@PathVariable注解是用于从request中接收请求的,两个都可以接收参数,关键点不同的是@RequestParam是从request里面拿取值,而@PathVariable是从一个URI模板里面来填充
@RestController
作用及范围:等同于@Controller + @ResponseBody
例子:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(annotation = Controller.class)
    String value() default "";
}
@ControllerAdvice
作用及范围:全局异常处理;全局数据绑定;全局数据预处理
@ControllerAdvice
public class MyGlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ModelAndView customException(Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", e.getMessage());
        mv.setViewName("error");
        return mv;
    }
}
@ControllerAdvice
public class MyGlobalExceptionHandler {
    @ModelAttribute(name = "md")
    public Map<String,Object> mydata() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gender", "女");
        return map;
    }
}
@ExceptionHandler
作用及范围:用于处理controller层面的异常
例子:
@ExceptionHandler({RuntimeException.class})
public ModelAndView fix(Exception ex){
    System.out.println("aaaa");
    return new ModelAndView("error",new ModelMap("ex",ex.getMessage()));
}
 
  
  
  
 
 
  
 
 
 