@Component注解的作用

简介: @Component注解的作用

Spring自带的@Component注解及扩展:

@Component:定义Spring管理Bean(也就是将标注@Component注解的类交由spring管理)

@AspectJ风格的切面可以通过@Compenent注解标识其为Spring管理Bean,而@Aspect注解不能被Spring自动识别并注册为Bean,必须通过@Component注解来完成

Java代码

@Component    
@Aspect    
public class TestAspect {    
    @Pointcut(value="execution(* *(..))")    
    private void pointcut() {}    
      
    @Before(value="pointcut()")    
    public void before() {    
        System.out.println("=======before");    
    }    
}   
AI 代码解读

通过@Component将切面定义为Spring管理Bean。

@Repository:

@Component扩展,被@Repository注解的POJO类表示DAO层实现,从而见到该注解就想到DAO层实现,使用方式和@Component相同;

@Service:

@Component扩展,被@Service注解的POJO类表示Service层实现,从而见到该注解就想到Service层实现,使用方式和@Component相同;

@Controller:

@Component扩展,被@Controller注解的类表示Web层实现,从而见到该注解就想到Web层实现,使用方式和@Component相同;

在使用Spring代理时,默认只有在public可见度的方法的@Transactional 注解才是有效的,其它可见度(protected、private、包可见)的方法上即使有@Transactional 注解也不会应用这些事务属性的,Spring也不会报错,如果你非要使用非公共方法注解事务管理的话,可考虑使用AspectJ。

Spring声明式事务实现其实就是Spring AOP+线程绑定实现,利用AOP实现开启和关闭事务,利用线程绑定(ThreadLocal)实现跨越多个方法实现事务传播。

补充:

@Configuration注解:
image.png

点进去可以看到@Component注解。

也就是说,@Configuration注解是声明一个IOC容器,把所有标记了@Bean注解的类注入到IOC容器中去。

就相当于xml配置文件:


<!--beans就是@Configuration注解 -->
<beans>
    <!--bean 就是一个个@Component注解声明的类 -->
    <bean></bean>
    <bean></bean>
    <bean></bean>
</beans>
AI 代码解读
目录
打赏
0
0
0
0
21
分享
相关文章
@Builder这个注解的作用
@Builder这个注解的作用
344 0
@EnableDiscoveryClient注解的作用
@EnableDiscoveryClient注解的作用 @EnableDiscoveryClient 及@EnableEurekaClient 类似,都是将一个微服务注册到Eureka Server(或其他 服务发现组件,例如Zookeeper、Consul等)
1671 0
|
26天前
|
@Inherited 注解的作用
@Inherited 注解的作用
|
9月前
|
@GrpcServise 注解的作用和使用
@GrpcServise 注解的作用和使用
80 0
@Resource注解是什么作用,和@bean区别是什么?
@Resource注解是什么作用,和@bean区别是什么?
295 0
@Configuration配置类注解的理解
@Configuration配置类注解的理解
157 0
@Configuration配置类注解的理解
SpringBoot【问题 01】借助@PostConstruct解决使用@Component注解的类用@Resource注入Mapper接口为null的问题(原因解析+解决方法)
SpringBoot【问题 01】借助@PostConstruct解决使用@Component注解的类用@Resource注入Mapper接口为null的问题(原因解析+解决方法)
988 0
Spring注解配置:@Configuration 和 @Component 区别及原理详解
随着`Spring Boot`的盛行,注解配置式开发受到了大家的青睐,从此告别了基于`Spring`开发的繁琐`XML`配置。这里先来提纲挈领的了解一下`Spring`内部对于配置注解的定义,如`@Component、@Configuration、@Bean、@Import`等注解,从功能上来讲,这些注解所负责的功能的确不相同,但是
445 1
Spring 如何通过反射获取controller 包下所有的类,以及类上的注解
Spring 如何通过反射获取controller 包下所有的类,以及类上的注解
338 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等