Spring Core

Spring Core

容器(创建并管理bean的容器)

创建:使用反射技术,创建bean的实例设计:使用工厂模式(BeanFactory)管理:容器中的每个bean,Spring容器默认按照单例方式管理,scope属性为singleton,可以通过设置<bean scope="prototype"/>更改为每次获取时创建不同的实例。

<!--业务层

Spring默认使用单例的方式管理Bean;默认状态下,获取Bean多次为同一个对象(hashcode相同)-->

<!-- <bean id="messageServiceImpl" class="com.chen.service.impl.MessageServiceImpl" /> -->

<!--默认为单例模式:scope属性为singleton-->

<!--<bean id="messageServiceImpl" class="com.chen.service.impl.MessageServiceImpl" scope="singleton"/>-->

<!--每次都是新实例scope属性为prototype -->

<!--<bean id="messageServiceBean" class="com.apesource.service.impl.MessageSeriviceImpl"/>-->

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

ApplicationContextcontext=newAnnotationConfigApplicationContext("com.apesource");

UserControlleruserController=(UserController)context.getBean("userController");

userController.execouteDosth();

ICO或者DI

⭐IOC:Inverse Of Control(控制翻转)⭐DI:Dependency Injection(依赖注入)💭思想:将项目中的类(组件)交给Spring容器管理,按照组件之间彼此的以来关系(采用xml配置文件或者注解),完成组件之间的注入,降低组件之间的耦合🌙三种注入方式:①属性注入②构造注入(使用有参构造方法进行注入)③接口注入

<beanid="messageControllerBean"class="com.apesource.web.MessageController">

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

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

<constructor-argname="messageService"ref="messageServiceBean"/>

<constructor-argname="message"value="哈哈哈哈"/>

</bean>

🌙三种配置方式:①XML:优势——配置内容直观清晰,扩展灵活劣势——配置繁琐②注解:优势——简洁劣势——扩展不灵活③JavaConfig:优势——借助IDE工具,确保配置内容准确劣势——配置代码比较多,扩展不灵活

注解

声明bean

@Component:组件@Controller:控制器组件@Service:业务层组件@Repository:数据访问层组件

声明注入

Spring Framework :⭐@Autowired :自动装配(默认按照类型自动装配) ,按照当前声明的接口类型,在容器中查找该接口实现类对象bean ,进行自动注入(装配)。⭐@Qualifier :按照bean名称自动装配,与@Autowired注解配合使用。按照当前指定的bean名称,在容器中查找该名称对应的bean ,进行自动注入(装配)。Java标准注解:⭐@Resource : javax扩展包提供的注解,完成自动注入 ,默认按照类型自动注入,也可以使用name属'性进行按名称自动注入

其他方式:

@primary:当前bean为主要bean,当发现多个相同类型的bean,以主要bean为首选@Scope("prototype") : 设置bean的作用域为每次获取时创建新的bean;默认为单例。@Configuration :设置当前类为配置类。(JavaConfig配置中使用)@Bean :设置当前方法为bean的创建方法,方法名即为bean的名称。( JavaConfig配置中使用)

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