注解配置bean

feat: 注解方式创建和注入bean

@Component Controller Service 注册bean

@Component
class UserService {

}

这样spring创建的bean的名字是userService

这些注解只有注释实现类有用,会创建相应的bean,注释interface没有任何效果。

Where should @Service annotation be kept? Interface or Implementation?

@Resource vs @Autowired 注入bean

https://blog.csdn.net/weixin_40423597/article/details/80643990

@Resource

如果指定了name或者type,找不到就报错。默认byName,找不到则byType。

@Autowired

默认按类型装配,加上@Autowired(required=false)即使不存在bean也不报错,会注入null。搭配@Qualifier("userServiceImpl")可以指定按名字匹配。

两者都可以对字段或者setter方法进行注解

研究下 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor

o513Bc-232315

@Autowired

pQQl0K-232613

@Resource @Inject

✅ @Service 和 @Resource 搭配使用

feat: @controller(value) 和 @resource(name)

@Service 注册创建bean,@Resource 注入bean。

  • 一个类只要被@Service注解并在扫描的包里,就会被创建bean,无论他是否被注入/使用。

  • 一个类如果没有被@Service注解,他的成员变量被@Resource注解的话,不会报错,但是注入的是null

@Service 加上 value 修改默认创建bean的名字。

@Resource 加上 name 修改默认注入时查找的bean的名字。

扫描和过滤包里的注解

https://www.bilibili.com/video/BV1ht411g7Zu?p=13

https://www.concretepage.com/spring/spring-component-scan-include-and-exclude-filter-example

egwJTQ-231618
2TOMZ2-232012
naNmD1-233259

当需要对包下需要扫描的类进行过滤时可以用pattern和filter过滤,没有自己试验,需要写的时候再学。

@Configuration搭配@Bean创建bean

JdbcTemplateBean.java 文件

注意@Bean对方法注解产生的bean的名字是方法名,比如 如果不设置(name = "jdbcTemplate")的话,名字就是getJdbcTemplate

https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html

To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory. By default, the bean name will be the same as the method name (see bean naming for details on how to customize this behavior). The following is a simple example of a @Bean method declaration:

Last updated

Was this helpful?