bean配置的方式
-
通过xml
这种方式较为繁琐,但是自定义的东西较多,id,ref都可自行定义;无需按照spring相关默认的方式进行注册
(在使用 XML 配置 Bean 时,ref 元素通常是用来引用其他已经定义的 Bean,并且是通过 Bean 的 id 来进行引用和注入的。这种方法使得在 XML 配置的 Spring 应用程序中可以灵活地管理和注入依赖) -
注解方式
如 常见的 @Resource @Autowired 等等 – 为什么他们能直接通过注解即可声明一个bean呢? 主要是因为(下面会说他们之间的区别)@Resource 是依赖 CommonAnnotationBeanPostProcessor 里面有对javax.annotation.Resource 注解的扫描
至于 service、component controller 的话则是依赖于 componentScan,依次遍历扫描到之后,将其注册成bean -
java 配置方式(依赖于 configuration 和 bean 注解)
较为推崇的则有:
- 注解自动装配
创建对象以及处理对象依赖关系,相关的注解:
@ComponentScan扫描器
@Configuration表明该类是配置类
@Component 指定把一个对象加入IOC容器
@Repository 作用同@Component; 在持久层使用
@Service 作用同@Component; 在业务逻辑层使用
@Controller 作用同@Component; 在控制层使用
@Resource 依赖关系
如果@Resource不指定值,那么就根据类型来找,相同的类型在IOC容器中不能有两个相同类型的bean,这里所说的类型【应该是同名、同类路径吧?】如果@Resource指定了值,那么就根据名字来找
@Resource和@Autowire
@Resource注解也可以完成属性注入。那它和@Autowired注解有什么区别?
- @Resource注解是JDK扩展包中的,也就是说属于JDK的一部分。所以该注解是标准注解,更加具有通用性。(USR-250标准中制定的注解类型。JSR是Java规范提案。)
- @Autowired注解是Spring框架自己的。
- @Resource注解默认根据名称装配byName,未指定name时,使用属性名作为name。通过name找不到的话会自动启动通过类型byType装配。
- @Autowired注解默认根据类型装配byType,如果想根据名称装配,需要配合@Qualifier注解一起用。
- @Resource注解用在属性上、setter方法上。
- @Autowired注解用在属性上、setter方法上、构造方法上、构造方法参数上。
- @Resource注解属于JDK扩展包,所以不在JDK当中,需要额外引入以下依赖:【如果是JDK8的话不需要额外引入依赖。高于JDK11或低于JDK8需要引入以下依赖
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>xxx</version>
</dependency>
补充:
- @Bean 方法中的参数
Spring 框架在处理 @Bean 方法中的参数时,默认的行为与 @Autowired 注解的工作方式是一致的 - 通用的xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
可以加上 这个 default-autowire="byName" >
<bean id="appinfo" class="APPInfoDO" >
<property name="appName" value="ABC"/>
</bean>
<bean id="aService" class="AService" >
</bean>
<!--日常为1.0.0.daily 预发和线上是1.0.0-->
<bean id="aService" class="AService" init-method="init">
<bean id="aClient" class="AClient" init-method="init">
<property name="info" ref="appinfo" />
<property name="aService" ref="aService" />
</bean>
</beans>