第三节 理解 SpringApplication

合集下载

Spring的ApplicationEvent的使用

Spring的ApplicationEvent的使用

Spring的ApplicationEvent的使用Spring的ApplicationEvent的使用Spring 3.0中提供了很多类似*Aware的类,其中ApplicationContextAware接口可以实现我们在初始化bean的时候给bean注入ApplicationConxt(Spring上下文对象)对象。

ApplicationContextAware接口提供了publishEvent方法,实现了Observe(观察者)设计模式的传播机制,实现了对bean的传播。

通过ApplicationContextAware我们可以把系统中所有ApplicationEvent传播给系统中所有的ApplicationListener。

因此,我们只需要构造好我们自己的ApplicationEvent和ApplicationListener,就可以在系统中实现相应的监听器。

下面以增加学生的示例来演示如何构造Spring的监听器,StudentAddEvent是监听的事件对象,StudentAddListener是事件的监听器(负责处理接收到的监听事件),StudentAddBean负责触发StudentAddEvent事件。

具体步骤如下:1. 定义StudentAddEvent监听事件新建StudentAddEvent类,实现抽象类org.springframework.context.ApplicationEvent StudentAddEvent类中需要实现自己的构造函数,具体代码如下:[java] view plaincopypackage com.trs.spring.event; import org.springframework.context.ApplicationEvent; /** * 增加学生的监听事件*/ public class StudentAddEvent extends ApplicationEvent { /** * */ private static final long serialVersionUID = 20L; /** * 学生姓名*/ private String m_sStudentName; /** * @param source */ public StudentAddEvent(Object source, String _sStudentName){ super(source); this.m_sStudentName = _sStudentName; } /** * 获取学生姓名* * @return */ public String getStudentName() { returnm_sStudentName; } }2. 定义StudentAddListener监听器新建StudentAddListener类,实现接口org.springframework.context.ApplicationListener中的onApplicationEvent方法,在该方法中只处理StudentAddEvent类型的ApplicationEvent事件,代码如下:[java] view plaincopypackage com.trs.spring.event; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; publicclass StudentAddListener implements ApplicationListener{ /* * (non-Javadoc) * * @see*org.springframework.context.ApplicationListener#onApplicatio nEvent(org * .springframework.context.ApplicationEvent) */ public void onApplicationEvent(ApplicationEvent_event) { // 1.判断是否是增加学生对象的事件if (!(_event instanceof StudentAddEvent)){ return; } // 2.是增加学生事件的对象,进行逻辑处理,比如记日志、积分等StudentAddEvent studentAddEvent = (StudentAddEvent)_event; System.out.println("增加了学生:::" + studentAddEvent.getStudentName()); } }3. 定义StudentAddBean触发StudentAddEvent事件新建StudentAddBean类,实现接口org.springframework.context.ApplicationContextAware中的setApplicationContext方法,在构造bean的时候注入Spring的上下文对象,以便通过Spring上下文对象的publishEvent方法来触发StudentAddEvent事件,具体代码如下:[java] view plaincopypackage com.trs.spring.event; importorg.springframework.beans.BeansException; importorg.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware;importorg.springframework.context.support.ClassPathXmlApplication Context; public class StudentAddBean implements ApplicationContextAware { /** * 定义Spring上下文对象*/ private ApplicationContextm_applicationContext = null; /* * (non-Javadoc) * * @see *org.springframework.context.ApplicationContextAware#setApp licationContext *(org.springframework.context.ApplicationContext) */ public void setApplicationContext(ApplicationContext_applicationContext) throws BeansException { this.m_applicationContext =_applicationContext; } /** * 增加一个学生* * @param _sStudentName */ public void addStudent(String _sStudentName) { // 1.构造一个增加学生的事件StudentAddEvent aStudentEvent = newStudentAddEvent( m_applicationContext,_sStudentName); // 2.触发增加学生事件m_applicationContext.publishEvent(aStudentEvent); } /** * @param args */ public static void main(String[] args) { String[] xmlConfig = new String[] { "applicationContext.xml" }; // 使用ApplicationContext来初始化系统ApplicationContext context = new ClassPathXmlApplicationContext( xmlCo nfig); StudentAddBean studentBean = (StudentAddBean)context .getBean("StudentAddBean"); studentBean.addStudent("我是第一个学生"); studentBean.addStudent("第二个学生已经添加"); } }4. applicationContext.xml配置文件<beanid="StudentAddBean"class="com.trs.spring.event.StudentAddBean"></bean&gt ;<bean id="StudentAddListener"class="com.trs.spring.event.StudentAddListener"></bean >。

SpringBootApplication注解原理及代码详解

SpringBootApplication注解原理及代码详解

SpringBootApplication注解原理及代码详解1、SpringBoot 启动main()@SpringBootApplicationpublic class TomcatdebugApplication {public static void main(String[] args) {SpringApplication.run(TomcatdebugApplication.class, args);}}1.1 @SpringBootApplication 注解,其实主要是@ComponentScan,@EnableAutoConfiguration,@SpringBootConfiguration三个注解@ComponentScan 注解:spring⾥有四⼤注解:@Service,@Repository,@Component,@Controller⽤来定义⼀个bean.@ComponentScan注解就是⽤来⾃动扫描被这些注解标识的类,最终⽣成ioc容器⾥的bean.可以通过设置@ComponentScan basePackages,includeFilters,excludeFilters属性来动态确定⾃动扫描范围,类型已经不扫描的类型. 默认情况下:它扫描所有类型,并且扫描范围是@ComponentScan注解所在配置类包及⼦包的类@SpringBootConfiguration 注解:@SpringBootConfiguration继承⾃@Configuration,⼆者功能也⼀致,标注当前类是配置类,并会将当前类内声明的⼀个或多个以@Bean注解标记的⽅法的实例纳⼊到spring容器中,并且实例名就是⽅法名。

demo 说明:(1)注⼊spring ioc bean@SpringBootConfigurationpublic class Config {@Beanpublic Map createMap(){Map map = new HashMap();map.put("username","gxz");map.put("age",27);return map;}}(2)调⽤:public static void main( String[] args ){//⽅式1 获取contextConfigurableApplicationContext context = SpringApplication.run(App.class, args);context.getBean(Runnable.class).run();context.getBean("createMap"); //注意这⾥直接获取到这个⽅法beanint age = (int) map.get("age");System.out.println("age=="+age);//⽅式2. 使⽤@Autowired注解,应⽤bean// @Autowired// Map createMap}@EnableAutoConfiguration 注解@EnableAutoConfiguration作⽤:从classpath中搜索所有的META-INF/spring.factories配置⽂件,然后将其中key为org.springframework.boot.autoconfigure.EnableAutoConfiguration的value加载到spring容器中。

springboot注解@SpringBootApplication分析

springboot注解@SpringBootApplication分析

springboot注解@SpringBootApplication分析@SpringBootApplication注解⽤在Spring Boot的⼊⼝类上⾯,是Spring Boot提供的应⽤启动相关的注解。

直接上注解的源码:@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })public @interface SpringBootApplication {@AliasFor(annotation = EnableAutoConfiguration.class, attribute = "exclude")Class<?>[] exclude() default {};@AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName")String[] excludeName() default {};@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")String[] scanBasePackages() default {};@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")Class<?>[] scanBasePackageClasses() default {};}@SpringBootApplication是⼀个复合注解查看源码,可以发现@SpringBootApplication是⼀个复合注解,包含了@SpringBootConfiguration,@EnableAutoConfiguration和@ComponentScan三个注解。

对Spring的理解

对Spring的理解

对Spring的理解1、Spring 是什么?Spring 是⼀个轻量级的 IoC 和 AOP 容器框架。

是为 Java 应⽤程序提供基础性服务的⼀套框架,⽬的是⽤于简化企业应⽤程序的开发,它使得开发者只需要关⼼业务需求。

常见的配置⽅式有三种:基于 XML 的配置、基于注解的配置、基于 Java 的配置。

主要由以下七个模块组成:(CC DAO MW)Spring Core:核⼼类库,提供 IOC 服务;Spring Context:提供框架式的 Bean 访问⽅式,以及企业级功能(JNDI、定时任务等);Spring AOP:AOP 服务;Spring DAO:对 JDBC 的抽象,简化了数据访问异常的处理;Spring ORM:对现有的 ORM 框架的⽀持;Spring Web:提供了基本的⾯向 Web 的综合特性,例如多⽅⽂件上传;Spring MVC:提供⾯向 Web 应⽤的 Model-View-Controller 实现。

2、Spring 的优点?(1)spring 属于低侵⼊式设计,代码的污染极低;(2)spring 的 DI 机制将对象之间的依赖关系交由框架处理,减低组件的耦合性;(3)Spring 提供了 AOP 技术,⽀持将⼀些通⽤任务,如安全、事务、⽇志、权限等进⾏集中式管理,从⽽提供更好的复⽤。

(4)spring 对于主流的应⽤框架提供了集成⽀持。

3、Spring 的 AOP 理解:实际案例:⽇志控制。

AOP,⼀般称为⾯向切⾯,作为⾯向对象的⼀种补充,⽤于将那些与业务⽆关,但却对多个对象产⽣影响的公共⾏为和逻辑,抽取并封装为⼀个可重⽤的模块,这个模块被命名为“切⾯”(Aspect),减少系统中的重复代码,降低了模块间的耦合度,同时提⾼了系统的可维护性。

可⽤于权限认证、⽇志、事务处理。

AOP 实现的关键在于代理模式,AOP 代理主要分为静态代理(拦截器)和动态代理。

(1)Spring AOP 使⽤的动态代理:Spring AOP 中的动态代理主要有两种⽅式,JDK 动态代理和 CGLIB 动态代理:@JDK 动态代理只提供接⼝的代理,不⽀持类的代理。

对Spring的理解

对Spring的理解

对Spring的理解1.是⼀个轻量级的框架,这个轻量级就体现在⾮侵⼊式上,即在代码实现过程中不需要继承Spring框架的相应类或实现相应接⼝。

2.Spring的核⼼就是IOC(控制反转) 和AOP,在Spring中,⽆需再在代码⾥进⾏以new的⽅式来使⽤了,所有的Bean对象都交由IOC容器进⾏管理(Bean实例对象的创建、属性值的设置、初始化、销毁整个⽣命周期都由IOC容器来管理),所以,第⼀个需要明⽩的就是所有的对象放在了⼀个统⼀的地⽅由Spring帮我们管理着。

并且,各个对象中所需要的其他依赖(就是⼀个对象中引⽤的其他对象,成员变量等)是通过依赖注⼊(DI)的⽅式进⾏传递,也就是说⽆需我们调⽤setter⽅法进⾏设置。

使⽤时直接从IOC容器中获取这些对象进⾏使⽤即可。

对象和对象之间的调⽤不会再以 new 这种硬编码的⽅式进⾏关联了,做到了解耦。

3.Spring中IOC容器有两种实现⽅式,⼀种是BeanFactory接⼝定义,⼀种是ApplicationContext接⼝定义(继承于BeanFactory实现)。

我们主要以ApplicationContext为主。

这⾥初始化IOC容器实际上就是创建ApplicationContent上下⽂对象的过程。

即ApplicationContent就表⽰的是IOC容器。

这⾥创建ApplicationContext时需要根据配置⽂件进⾏初始化IOC容器,配置⽂件⾥就是告诉了Spring需要将哪些指定的Bean放到IOC容器中管理起来。

配置的⽅式有多种,从类路径下加载⼀个或多个xml ⽂件、从⼀个或多个基于java的配置类中加载、从⽂件系统下的⼀个或多个xml⽂件中加载。

基本都类似,这⾥我们看下从类路径中加载。

ApplicationContext ctx=new ClassPathXmlApplicationContext("application.xml"),其中ClassPathXmlApplicationContext类为ApplicationContext接⼝的实现类,当然加载⽅式不同,它还有其他的实现类。

spring学习-ApplicationContext-spring上下文深入理解

spring学习-ApplicationContext-spring上下文深入理解

spring学习-ApplicationContext-spring上下⽂深⼊理解4⽉份开始复习⼀遍spring相关知识。

让⾃⼰巩固⼀下spring⼤法的深奥益处,所以就看了⼤佬的博客,转载留下来⽇后继续研读。

认为重点的标记为红⾊Spring有两个核⼼接⼝:BeanFactory和ApplicationContext,其中ApplicationContext是BeanFactory的⼦接⼝。

他们都可代表Spring容器,Spring容器是⽣成Bean实例的⼯⼚,并且管理容器中的Bean。

Bean是Spring管理的基本单位,在基于Spring的Java EE应⽤中,所有的组件都被当成Bean处理,包括数据源、Hibernate的SessionFactory、事务管理器等。

在Spring中,Bean的是⼀个⾮常⼴义的概念,任何的Java对象、Java组件都被当成Bean处理。

⽽且应⽤中的所有组件,都处于Spring的管理下,都被Spring以Bean的⽅式管理,Spring负责创建Bean实例,并管理他们的⽣命周期。

Bean在Spring容器中运⾏,⽆须感受Spring容器的存在,⼀样可以接受Spring的依赖注⼊,包括Bean属性的注⼊,协作者的注⼊、依赖关系的注⼊等。

Spring容器负责创建Bean实例,所以需要知道每个Bean的实现类,Java程序⾯向接⼝编程,⽆须关⼼Bean实例的实现类;但是Spring容器必须能够精确知道每个Bean实例的实现类,因此Spring配置⽂件必须精确配置Bean实例的实现类。

⼀、Spring容器Spring容器最基本的接⼝就是BeanFactor。

BeanFactory负责配置、创建、管理Bean,他有⼀个⼦接⼝:ApplicationContext,因此也称之为Spring上下⽂。

Spring容器负责管理Bean与Bean之间的依赖关系。

BeanFactory接⼝包含以下⼏个基本⽅法:Ø Boolean containBean(String name):判断Spring容器是否包含id为name的Bean实例。

spring学习(十二)--spring中WebApplicationInitializer解析

spring学习(十二)--spring中WebApplicationInitializer解析

spring学习(⼗⼆)--spring中WebApplicationInitializer解析 上⽂中讲解了如何通过WebApplicationInitializer取代Web.xml进⾏spring容器的启动,WebApplicationInitializer是⼀个接⼝,通过实现WebApplicationInitializer,在其中可以添加servlet,listener等。

在Web容器启动的时候,spring-web会通过SPI机制,加载这个接⼝的实现类,从⽽起到web.xml相同的作⽤。

下⾯就看⼀下这个接⼝的详细内容:public interface WebApplicationInitializer {void onStartup(ServletContext servletContext) throws ServletException;}WebApplicationInitializer只有⼀个⽅法,⽐较简单,看不出什么头绪。

在WebApplicationInitializer同级别有个SpringServletContainerInitializer类,我们来看下这个类的代码:package org.springframework.web;@HandlesTypes(WebApplicationInitializer.class)public class SpringServletContainerInitializer implements ServletContainerInitializer {@Overridepublic void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)throws ServletException {List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();if (webAppInitializerClasses != null) {for (Class<?> waiClass : webAppInitializerClasses) {// Be defensive: Some servlet containers provide us with invalid classes,// no matter what @HandlesTypes says...if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&WebApplicationInitializer.class.isAssignableFrom(waiClass)) {try {initializers.add((WebApplicationInitializer) waiClass.newInstance());}catch (Throwable ex) {throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);}}}}if (initializers.isEmpty()) {servletContext.log("No Spring WebApplicationInitializer types detected on classpath");return;}AnnotationAwareOrderComparator.sort(initializers);servletContext.log("Spring WebApplicationInitializers detected on classpath: " + initializers);for (WebApplicationInitializer initializer : initializers) { //这⾥指定了调⽤的类的⽅法,onStartup()initializer.onStartup(servletContext);}}}SpringServletContainerInitializer这个类⾥也有个onStartup⽅法,看⼀下它的逻辑。

application 怎么读

application 怎么读

application 怎么读
“application”是一个英语单词,发音为英式音标/ˌæplɪˈkeɪʃn/ 和美式音标/ˌæplɪˈkeɪʃn/。

这个单词的发音可以拆分为两个音节:“ap-”和“-plication”,并在“ap-”上放置重音。

在发音时,注意保持整个单词的音调平稳,并清晰地发出每个音节。

“application”的基本含义是“申请”或“请求”,它通常用于描述个人或组织向另一方提出的正式请求或申请。

这个单词在求职、入学、贷款等场合中非常常见,比如填写“application form”(申请表)或发送“application letter”(申请信)。

此外,“application”还可以表示“应用”或“使用”的意思,即如何利用某种知识、技能或工具来实现特定目的。

例如,在科技领域,“application”可以指代手机或电脑上的“应用程序”(app),这些程序可以帮助用户完成各种任务,如浏览网页、编辑文档、玩游戏等。

除此之外,“application”还可以表示“适用性”或“实用性”,即某物或某方法是否适合用于特定情境或目的。

这个含义通常用于评估某种理论、技术或产品的实际应用价值。

总之,“application”是一个具有多种含义的单词,可以用于各种语境中描述申请、应用、使用以及适用性和实用性等概念。

在发音时,注意将重音放在正确的音节上,并保持清晰的发音。

同时,在
使用时也需要注意具体语境和语法规则,以确保表达的准确性和清晰度。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

配置 Spring Boot Bean 源
Java 配置 Class 或 XML 上下文配置文件集合,用于 Spring Boot BeanDefinitionLoader读取,并且将配置源解析加载为Spring Bean 定义
数量:一个或多个以上
Java 配置 Class
用于 Spring 注解驱动中 Java 配置类,大多数情况是 Spring 模式注解所标注的类,如@Configuration。

XML 上下文配置文件
用于 Spring 传统配置驱动中的 XML 文件。

推断 Web 应用类型
根据当前应用 ClassPath 中是否存在相关实现类来推断 Web 应用的类型,包括:
Web Reactive :WebApplicationType.REACTIVE
Web Servlet:WebApplicationType.SERVLET
非 Web:WebApplicationType.NONE
参考方法:org.springframework.boot.SpringApplication#deduceWebApplicationType
private WebApplicationType deduceWebApplicationType() {
if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)
&&!ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : WEB_ENVIRONMENT_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
return WebApplicationType.SERVLET;
}
推断引导类(Main Class)
根据 Main 线程执行堆栈判断实际的引导类
参考方法:org.springframework.boot.SpringApplication#deduceMainApplicationClass
private Class<?>deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace=new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
加载应用上下文初始器(ApplicationContextInitializer)利用 Spring 工厂加载机制,实例化ApplicationContextInitializer实现类,并排序对象集合。

实现
private<T>Collection<T>getSpringFactoriesInstances(Class<T>type,
Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String>names=new LinkedHashSet<>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T>instances=createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
技术
实现类:org.springframework.core.io.support.SpringFactoriesLoader
配置资源:META-INF/spring.factories
排序:AnnotationAwareOrderComparator#sort
加载应用事件监听器(ApplicationListener)
利用 Spring 工厂加载机制,实例化ApplicationListener实现类,并排序对象集合
SpringApplication 运行阶段
加载SpringApplication运行监听器(SpringApplicationRunListeners)
利用 Spring 工厂加载机制,读取SpringApplicationRunListener对象集合,并且封装到组合类SpringApplicationRunListeners
运行SpringApplication运行监听器(SpringApplicationRunListeners)
SpringApplicationRunListener监听多个运行状态方法:
监听方法阶段说明Spring Boot 起始版本starting()Spring 应用刚启动 1.0
environmentPrepared(ConfigurableEnvironment)ConfigurableEnvironment准备妥当,允许将其调整 1.0
contextPrepared(ConfigurableApplicationContext)ConfigurableApplicationContext准备妥当,允许将其调整 1.0
contextLoaded(ConfigurableApplicationContext)ConfigurableApplicationContext已装载,但仍未启动 1.0
started(ConfigurableApplicationContext)ConfigurableApplicationContext已启动,此时 Spring Bean 已初始化完成 2.0
running(ConfigurableApplicationContext)Spring 应用正在运行 2.0
failed(ConfigurableApplicationContext,Throwable)Spring 应用运行失败 2.0
监听 Spring Boot 事件 / Spring 事件
Spring Boot 通过SpringApplicationRunListener 的实现类EventPublishingRunListener利用 Spring Framework 事件API ,广播 Spring Boot 事件。

Spring Framework 事件/监听器编程模型
Spring 应用事件
普通应用事件:ApplicationEvent
应用上下文事件:ApplicationContextEvent
Spring 应用监听器
接口编程模型:ApplicationListener
注解编程模型:@EventListener
Spring 应用事广播器
接口:ApplicationEventMulticaster
实现类:SimpleApplicationEventMulticaster
执行模式:同步或异步。

相关文档
最新文档