@Component @Bean区别

@Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean,@Component(@Controller、@Service、@Repository)通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中。

 @Bean注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。通常方法体中包含了最终产生bean实例的逻辑,并且实例名就是方法名
(引入第三方的类时也要用@bean)

当需要强制指定实例化bean的顺序,可以通过@Order或@DependsOn注解来实现

@Bean相当于Spring配置文件中的<bean />标签可以在Spring容器中注入一个bean

@Configuration
public class DemoConfiguration {

    @Bean
    public IdGen idGen () {
        return new IdGen ();
    }

}
View Code

@Bean 也可以不用写在@Configuration中写在springboot的启动类中也行

@SpringBootApplication
public class SystemApplication {
    public static void main(String[] args) {
        SpringApplication.run(SystemApplication.class,args);
    }
    @Bean
    public IdWorker idWorker(){
        return  new IdWorker();
    }

}

原因在于 : 

@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan

 

@Component修饰类
@Component
public class JwtInterceptor 
@Component   @Bean修饰的类引用时都是通过 @Autowired 引用的
@Autowired
private JwtInterceptor jwtInterceptor;

 

posted @ 2020-02-11 14:35  Angry-rookie  阅读(150)  评论(0)    收藏  举报