springBoot注解

1 ApplicationRunner 

是一个接口,里面定义一个run(ApplicationArguments args)方法,我们需要自己写一个类去实现这个这接口,并实现接口里面的run(ApplicationArguments args)方法。启动之后直接执行某一段代码

2 EnableAsync

EnableAsync注解的意思是可以异步执行,就是开启多线程的意思。可以标注在方法、类上

@Component
public class Task {
    @Async
    public void doTaskOne() throws Exception {
        // 同上内容,省略
    }
    @Async
    public void doTaskTwo() throws Exception {
        // 同上内容,省略
    }
    @Async
    public void doTaskThree() throws Exception {
        // 同上内容,省略
    }
}
@SpringBootApplication
@EnableAsync
public class Application {

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

}

3 EnableScheduling

要实现计划任务,首先通过在配置类注解@EnableScheduling来开启对计划任务的支持,然后在要执行计划任务的方法上注解@Scheduled,声明这是一个计划任务。

Spring通过@Scheduled支持多种类型的计划任务,包含cron、fixDelay、fixRate等。

4 @controller 控制器(注入服务)
用于标注控制层,相当于struts中的action层

5 @service 服务(注入dao)
用于标注服务层,主要用来进行业务的逻辑处理

6 @repository @Mapper(实现dao访问)

@Mapper注解是mybatis的注解,是用来说明这个是一个Mapper,对应的xxxMapper.xml就是来实现这个Mapper。然后再server层使用@Autowired注解引用进来,会出现这样的情况,但是并不影响使用。

这是因为@Autowired是spring的注解,提示找不到相应的bean。如果有强迫症的同学,可以使用@Resource注解,因为这个是JDK的注解。

@Repository注解是Spring的注解,使用该注解和@Autowired注解,就不会出现爆红的情况了,原因很简单,因为@Repository注解是Sring的注解,把当前类注册成一个bean了。如下图:

 

这里的@Mapper也是可以去掉的,但是要在启动类上加上
@MapperScan(value = {"com.bf.spring4.mapper"})

@Component 和 @Bean 的区别是什么?

1.作用对象不同:@Component 注解作用于类,而 @Bean 注解作用于方法、2.@Component 通常是通过路径扫描来自动侦测以及自动装配到 Spring 容器中(我们可以使用 @ComponentScan 注解定义要扫描的路径从中找出标识了需要装配的类自动装配到 Spring 的 bean 容器中)。@Bean 注解通常是我们在标有该注解的方法中定义产生这个 bean,@Bean 告诉了 Spring 这是某个类的实例,当我们需要用它的时候还给我。3.@Bean 注解比 @Component 注解的自定义性更强,而且很多地方我们只能通过 @Bean 注解来注册 bean。比如当我们引用第三方库中的类需要装配到 Spring 容器时,只能通过 @Bean 来实现。

(把普通pojo实例化到spring容器中,相当于配置文件中的 <bean id="" class=""/>)

泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类。
7  
PostConstruct

@PostConstruct注解好多人以为是Spring提供的。其实是Java自己的注解。

Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,
并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。 通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序: Constructor(构造方法) 
-> @Autowired(依赖注入) -> @PostConstruct(注释的方法)

 

posted @ 2021-04-20 15:10  夕阳下的无名草  阅读(101)  评论(0编辑  收藏  举报