Spring core 小结

Spring core

容器

创建并管理bean的容器

创建:使用反射技术,创建bean的实例

设计:使用工厂模式(BeanFactory)

管理:容器中的每个bean,Spring容器默认按照单例方式管理,可以通过设置<bean scope="prototype"/>更改为每次获取时创建不同的实例

ApplicationContext

ClassPathXmlApplicationContext:在classpath路径下加载xml配置文件,完成Spring容器的加载;或者,采用注解方式时,需要在xml配置文件中使用context:component-scan/完成类扫描。

AnnotationConfigApplicationContext:基于注解配置的Spring容器加载方式。

IOC或DI

IOC:Inverse Of Control(控制反转)

DI:Dependency Injection(依赖注入)

思想:将项目中的类(组件)交给Spring容器管理,按照组件之间彼此的依赖关系(采用xml配置文件或者注解),完成组件之间的注入,降低组件之间的耦合。

三种注入方式

1.属性(setter)注入

将容器中的messageServiceBean,注入给当前Controller的messageService属性(通过该属性的setter)

<property name="messageService" ref="messageServiceBean"/>

2.构造注入(使用有参构造方法进行注入)

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n19" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> public MessageController(String defaultMessage,IMessageService messageService){
System.out.println("默认消息为:"+defaultMessage);
this.messageService=messageService;
} ```
<constructor-arg name="messageService" ref="messageServiceBean"/>
<constructor-arg name="defaultMessage" value="默认消息模板"/></pre>

3.接口注入

注解

1.声明bean

@Component:组件

@Controller:控制器组件

@Service:业务层组件

@Repository:数据访问层组件

2.声明注入

Spring Framework

@Autowired:自动装配(默认按照类型自动装配),按照当前声明的接口类型,在容器中查找该接口的实现类对象bean,进行自动注入(装配)

@Qualifier:按照bean名称自动装配,与Autowired注解配合使用。按照当前指定的bean名称,在容器中查找该名称对应的bean,进行自动注入(装配)。

Java标准注解

@Resource:javax拓展包提供的注解,完成自动注入,默认按照类型自动注入,也可以使用name属性按名称自动注入

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。