springboot中@Bean的注解作⽤
⼀.@bean的作⽤
Spring的@Bean注解⽤于告诉⽅法,产⽣⼀个Bean对象,然后这个Bean对象交给Spring管理。Spring只会调⽤⼀次,将这个Bean对象放在⾃⼰的IOC容器中。
通俗的将就是在服务启动时,实例化⼀个对象放到ioc容器中,在需要初始化的实例,⽅法,内容时使⽤。
未指定bean 的名称,默认采⽤的是 "⽅法名" + "⾸字母⼩写"的配置⽅式
⼆.案例
1.定义⼀个配置⽂件:
package com.ljf.spring.boot.fig;
import com.ljf.spring.boot.demo.quartz.job.MyDefineQuartz;
import com.ljf.spring.boot.del.User;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
/**
* @ClassName: QuartsConfig
* @Description: TODO
* @Author: liujianfu
* @Date: 2020/07/27 09:13:13
* @Version: V1.0
**/
@Configuration
public class QuartsConfig {
/**
* 1.创建Job对象
*/
@Bean
public JobDetailFactoryBean jobDetailFactoryBean(){
System.out.println("初始化,创建job对象......");
JobDetailFactoryBean factory = new JobDetailFactoryBean();
//关联我们⾃⼰的Job类
factory.setJobClass(MyDefineQuartz.class);
return factory;
}
/**
* 2.Cron Trigger
*/
@Bean
public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean){
System.out.println("初始化,trigger对象......");
CronTriggerFactoryBean factory = new CronTriggerFactoryBean();
factory.Object());
spring ioc注解
//设置触发时间
factory.setCronExpression("0/2 * * * * ?");
return factory;
}
/**
* 3.创建Scheduler对象
*/
@Bean
public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean cronTriggerFactoryBean,User u){
public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean cronTriggerFactoryBean,User u){        System.out.println("初始化,创建scheduler对象......");
SchedulerFactoryBean factory = new SchedulerFactoryBean();
//关联trigger
factory.Object());
System.out.println("初始化u的对象:"+u.getName());
return factory;
}
/**
* @author liujianfu
* @description
* @date 2020/7/27 0027 下午 12:26
* @param []
* @return com.ljf.spring.boot.del.User
*/
@Bean
public User initUser(){
User u=new User();
u.setId(23);
u.setName("ljf");
return u;
}
}
2.启动类:
package com.ljf.spring.boot.demo.quartz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*/
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
System.out.println( "spring boot 和quarts集成程序启动成功!" );
}
}
3.结果:可以看到服务启动时候,添加@bean的⽅法都实例化了⼀个对象,都进⾏了执⾏。
四案例⼆

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。