1.测试引入
我们这里用到的maven项目,搭建我就不具体解释了
我就把需要引入的依赖引入了,我的jdk版本是jdk1.8
依赖只需要引入2个
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
</dependencies>
2.首先我们先定义一个持久层的
UserDao .java
public class UserDao {
/**
* @Author 丛硕
* @Description //TODO 这个充当Dao的保存方法
* @Date 14:40 2019/12/19 0019
* @Param
* @return
**/
public void save(){
System.out.println("我是Dao保存方法");
}
3.定义Service层
UserService .java
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void save(){
userDao.save();
System.out.println("我还是service 的保存 方法");
}
4.定义Controller层
UserController .java
public class UserController {
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
public void save(){
userService.save();
System.out.println("我是Controller 的 保存方法");
}
}
5.配置xml文件
UserDao.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
https://www.springframework.org/schema/beans/spring-beans.xsd
">
<bean id="userDao" class="com.cs.user.dao.UserDao"></bean>
<bean id="userService" class="com.cs.user.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userController" class="com.cs.user.controller.UserController">
<property name="userService" ref="userService"/>
</bean>
</beans>
6.提供测试类
TestXML .java
public class TestXML {
@Test
public void springXml(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("UserDao.xml");
UserController bean = applicationContext.getBean(UserController.class);
bean.save();
}
}
7.前面工作已经做好 让我们来进入Spring Ioc的世界吧
1.首先我们先了解一下ApplicationContext,
在org.springframework.beans和org.springframework.context包是Spring框架的IoC容器的基础。该 BeanFactory 界面提供了一种高级配置机制,能够管理任何类型的对象。 ApplicationContext 是的子接口BeanFactory。它增加了:
与Spring的AOP功能轻松集成
消息资源处理(用于国际化)
活动发布
应用层特定的上下文,例如WebApplicationContext 用于Web应用程序中的。
简而言之,BeanFactory提供了配置框架和基本功能,并ApplicationContext增加了更多针对企业的功能。该ApplicationContext是对一个完整的超集BeanFactory。
在Spring中,构成应用程序主干并由Spring IoC容器管理的对象称为bean。Bean是由Spring IoC容器实例化,组装和以其他方式管理的对象。否则,bean仅仅是应用程序中许多对象之一。Bean及其之间的依赖关系反映在容器使用的配置元数据中。
该org.springframework.context.ApplicationContext接口代表Spring IoC容器,并负责实例化,配置和组装Bean。容器通过读取配置元数据来获取有关要实例化,配置和组装哪些对象的指令。配置元数据以XML,Java批注或Java代码表示。它使您能够表达组成应用程序的对象以及这些对象之间的丰富相互依赖关系。
ApplicationContextSpring提供了该接口的几种实现。在独立应用程序中,通常创建ClassPathXmlApplicationContext 或的实例 FileSystemXmlApplicationContext。尽管XML是定义配置元数据的传统格式,但是您可以通过提供少量XML配置来声明性地启用对这些其他元数据格式的支持,从而指示容器将Java注释或代码用作元数据格式。
让我们先用图来描述一下上面叙述的事情
这里我来解释一下
业务对象:就是你代码中写的逻辑类
配置元数据:java的实体类
2.了解xml文件的配置
3.下面让我们进入spring 的内部
首先当我们运行Test测试类时 下面的代码就会执行
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("UserDao.xml");
ApplicationContext 是接口,而ClassPathApplicationContext是ApplicationContext的一个实现类,(这就是我们所说的父类引用指向子类对象)
接下来他会进入
//configLocation = UserDao.xml
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.context.support;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
@Nullable
private Resource[] configResources;
public ClassPathXmlApplicationContext() {
}
public ClassPathXmlApplicationContext(ApplicationContext parent) {
super(parent);
}
/*
* 1.首先会进入到一个带配置文件的有参构造
* param : configLocation -> UserDao.xml 配置文件名称
* true : 代表是否需要进行刷新
* (ApplicationContext)null :传入的父类
*
* 这时我们认为这是一个Spring 容器的初始化
*/
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[]{configLocation}, true, (ApplicationContext)null);
}
public ClassPathXmlApplicationContext(String... configLocations) throws BeansException {
this(configLocations, true, (ApplicationContext)null);
}
public ClassPathXmlApplicationContext(String[] configLocations, @Nullable ApplicationContext parent) throws BeansException {
this(configLocations, true, parent);
}
/**
* 2.进入此构造方法
*
* params : configLocations -> UserDao.xml
* 这里需要解释一下为什么是数组:因为我们传入的xml可以是多个
* refresh -> true 是否需要进行刷新
* (ApplicationContext)null -> null 指的是传入的是ApplicationContext子类对象
*
*
*/
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
this(configLocations, refresh, (ApplicationContext)null);
}
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
super(parent);
//设置属性
this.setConfigLocations(configLocations);
if (refresh) {
//执行刷新方法 之前把所有可能出现的错误判断一遍
//刷新
this.refresh();
}
}
public ClassPathXmlApplicationContext(String path, Class<?> clazz) throws BeansException {
this(new String[]{path}, clazz);
}
public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz) throws BeansException {
this(paths, clazz, (ApplicationContext)null);
}
public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz, @Nullable ApplicationContext parent) throws BeansException {
super(parent);
Assert.notNull(paths, "Path array must not be null");
Assert.notNull(clazz, "Class argument must not be null");
this.configResources = new Resource[paths.length];
for(int i = 0; i < paths.length; ++i) {
this.configResources[i] = new ClassPathResource(paths[i], clazz);
}
this.refresh();
}
@Nullable
protected Resource[] getConfigResources() {
return this.configResources;
}
}
然后会进入一个ClassPathXmlApplicationContext的构造函数
package org.springframework.context.support;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
public abstract class AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext implements BeanNameAware, InitializingBean {
@Nullable
private String[] configLocations; //定义存放配置文件的数组
private boolean setIdCalled = false;
public AbstractRefreshableConfigApplicationContext() {
}
public AbstractRefreshableConfigApplicationContext(@Nullable ApplicationContext parent) {
super(parent);
}
public void setConfigLocation(String location) {
this.setConfigLocations(StringUtils.tokenizeToStringArray(location, ",; \t\n"));
}
/**
* 3.
* locations -> UserDao.xml 传入xml的对象
*
*
*
*
*/
public void setConfigLocations(@Nullable String... locations) {
// 判断 配置文件对象是否为空
if (locations != null) {
//在进行判断 传入异常信息
Assert.noNullElements(locations, "Config locations must not be null");
//给存放配置文件的数组 设置长度
this.configLocations = new String[locations.length];
//循环遍历给 数组赋值
for(int i = 0; i < locations.length; ++i) {
this.configLocations[i] = this.resolvePath(locations[i]).trim();
}
} else {
this.configLocations = null;
}
}
@Nullable
protected String[] getConfigLocations() {
return this.configLocations != null ? this.configLocations : this.getDefaultConfigLocations();
}
@Nullable
protected String[] getDefaultConfigLocations() {
return null;
}
/**
* 7.解决路径问题
* path -> UserDao.xml
*
*/
protected String resolvePath(String path) {
return this.getEnvironment().resolveRequiredPlaceholders(path);
}
public void setId(String id) {
super.setId(id);
this.setIdCalled = true;
}
public void setBeanName(String name) {
if (!this.setIdCalled) {
super.setId(name);
this.setDisplayName("ApplicationContext '" + name + "'");
}
}
public void afterPropertiesSet() {
if (!this.isActive()) {
this.refresh();
}
}
}
=
=
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Supplier;
import org.springframework.lang.Nullable;
public abstract class Assert {
public Assert() {
}
public static void state(boolean expression, String message) {
if (!expression) {
throw new IllegalStateException(message);
}
}
public static void state(boolean expression, Supplier<String> messageSupplier) {
if (!expression) {
throw new IllegalStateException(nullSafeGet(messageSupplier));
}
}
/** @deprecated */
@Deprecated
public static void state(boolean expression) {
state(expression, "[Assertion failed] - this state invariant must be true");
}
public static void isTrue(boolean expression, String message) {
if (!expression) {
throw new IllegalArgumentException(message);
}
}
public static void isTrue(boolean expression, Supplier<String> messageSupplier) {
if (!expression) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/** @deprecated */
@Deprecated
public static void isTrue(boolean expression) {
isTrue(expression, "[Assertion failed] - this expression must be true");
}
public static void isNull(@Nullable Object object, String message) {
if (object != null) {
throw new IllegalArgumentException(message);
}
}
public static void isNull(@Nullable Object object, Supplier<String> messageSupplier) {
if (object != null) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/** @deprecated */
@Deprecated
public static void isNull(@Nullable Object object) {
isNull(object, "[Assertion failed] - the object argument must be null");
}
public static void notNull(@Nullable Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}
public static void notNull(@Nullable Object object, Supplier<String> messageSupplier) {
if (object == null) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/** @deprecated */
@Deprecated
public static void notNull(@Nullable Object object) {
notNull(object, "[Assertion failed] - this argument is required; it must not be null");
}
public static void hasLength(@Nullable String text, String message) {
if (!StringUtils.hasLength(text)) {
throw new IllegalArgumentException(message);
}
}
public static void hasLength(@Nullable String text, Supplier<String> messageSupplier) {
if (!StringUtils.hasLength(text)) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/** @deprecated */
@Deprecated
public static void hasLength(@Nullable String text) {
hasLength(text, "[Assertion failed] - this String argument must have length; it must not be null or empty");
}
public static void hasText(@Nullable String text, String message) {
if (!StringUtils.hasText(text)) {
throw new IllegalArgumentException(message);
}
}
public static void hasText(@Nullable String text, Supplier<String> messageSupplier) {
if (!StringUtils.hasText(text)) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/** @deprecated */
@Deprecated
public static void hasText(@Nullable String text) {
hasText(text, "[Assertion failed] - this String argument must have text; it must not be null, empty, or blank");
}
public static void doesNotContain(@Nullable String textToSearch, String substring, String message) {
if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) && textToSearch.contains(substring)) {
throw new IllegalArgumentException(message);
}
}
public static void doesNotContain(@Nullable String textToSearch, String substring, Supplier<String> messageSupplier) {
if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) && textToSearch.contains(substring)) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/** @deprecated */
@Deprecated
public static void doesNotContain(@Nullable String textToSearch, String substring) {
doesNotContain(textToSearch, substring, () -> {
return "[Assertion failed] - this String argument must not contain the substring [" + substring + "]";
});
}
public static void notEmpty(@Nullable Object[] array, String message) {
if (ObjectUtils.isEmpty(array)) {
throw new IllegalArgumentException(message);
}
}
public static void notEmpty(@Nullable Object[] array, Supplier<String> messageSupplier) {
if (ObjectUtils.isEmpty(array)) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/** @deprecated */
@Deprecated
public static void notEmpty(@Nullable Object[] array) {
notEmpty(array, "[Assertion failed] - this array must not be empty: it must contain at least 1 element");
}
/**
* 5.再次进行判断
* array -> 本地配置文件数组对象
* message -> 异常信息
*
* 增强代码的稳定性 防止程序员传入像 new Array{"UserDao.xml",""}这样的对象
*
*
*/
public static void noNullElements(@Nullable Object[] array, String message) {
//判断数组是否为空
if (array != null) {
//把数组 赋值给一个新的数组
Object[] var2 = array;
//得到数组的长度
int var3 = array.length;
//进行循环遍历 判断 那个为空
for(int var4 = 0; var4 < var3; ++var4) {
//依次获取 数组里的对象
Object element = var2[var4];
//判断 对象是否为空
if (element == null) {
//为空抛出异常
throw new IllegalArgumentException(message);
}
}
}
}
public static void noNullElements(@Nullable Object[] array, Supplier<String> messageSupplier) {
if (array != null) {
Object[] var2 = array;
int var3 = array.length;
for(int var4 = 0; var4 < var3; ++var4) {
Object element = var2[var4];
if (element == null) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
}
}
/** @deprecated */
@Deprecated
public static void noNullElements(@Nullable Object[] array) {
noNullElements(array, "[Assertion failed] - this array must not contain any null elements");
}
public static void notEmpty(@Nullable Collection<?> collection, String message) {
if (CollectionUtils.isEmpty(collection)) {
throw new IllegalArgumentException(message);
}
}
public static void notEmpty(@Nullable Collection<?> collection, Supplier<String> messageSupplier) {
if (CollectionUtils.isEmpty(collection)) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/** @deprecated */
@Deprecated
public static void notEmpty(@Nullable Collection<?> collection) {
notEmpty(collection, "[Assertion failed] - this collection must not be empty: it must contain at least 1 element");
}
public static void noNullElements(@Nullable Collection<?> collection, String message) {
if (collection != null) {
Iterator var2 = collection.iterator();
while(var2.hasNext()) {
Object element = var2.next();
if (element == null) {
throw new IllegalArgumentException(message);
}
}
}
}
public static void noNullElements(@Nullable Collection<?> collection, Supplier<String> messageSupplier) {
if (collection != null) {
Iterator var2 = collection.iterator();
while(var2.hasNext()) {
Object element = var2.next();
if (element == null) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
}
}
public static void notEmpty(@Nullable Map<?, ?> map, String message) {
if (CollectionUtils.isEmpty(map)) {
throw new IllegalArgumentException(message);
}
}
public static void notEmpty(@Nullable Map<?, ?> map, Supplier<String> messageSupplier) {
if (CollectionUtils.isEmpty(map)) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/** @deprecated */
@Deprecated
public static void notEmpty(@Nullable Map<?, ?> map) {
notEmpty(map, "[Assertion failed] - this map must not be empty; it must contain at least one entry");
}
public static void isInstanceOf(Class<?> type, @Nullable Object obj, String message) {
notNull(type, (String)"Type to check against must not be null");
if (!type.isInstance(obj)) {
instanceCheckFailed(type, obj, message);
}
}
public static void isInstanceOf(Class<?> type, @Nullable Object obj, Supplier<String> messageSupplier) {
notNull(type, (String)"Type to check against must not be null");
if (!type.isInstance(obj)) {
instanceCheckFailed(type, obj, nullSafeGet(messageSupplier));
}
}
public static void isInstanceOf(Class<?> type, @Nullable Object obj) {
isInstanceOf(type, obj, "");
}
public static void isAssignable(Class<?> superType, @Nullable Class<?> subType, String message) {
notNull(superType, (String)"Super type to check against must not be null");
if (subType == null || !superType.isAssignableFrom(subType)) {
assignableCheckFailed(superType, subType, message);
}
}
public static void isAssignable(Class<?> superType, @Nullable Class<?> subType, Supplier<String> messageSupplier) {
notNull(superType, (String)"Super type to check against must not be null");
if (subType == null || !superType.isAssignableFrom(subType)) {
assignableCheckFailed(superType, subType, nullSafeGet(messageSupplier));
}
}
public static void isAssignable(Class<?> superType, Class<?> subType) {
isAssignable(superType, subType, "");
}
private static void instanceCheckFailed(Class<?> type, @Nullable Object obj, @Nullable String msg) {
String className = obj != null ? obj.getClass().getName() : "null";
String result = "";
boolean defaultMessage = true;
if (StringUtils.hasLength(msg)) {
if (endsWithSeparator(msg)) {
result = msg + " ";
} else {
result = messageWithTypeName(msg, className);
defaultMessage = false;
}
}
if (defaultMessage) {
result = result + "Object of class [" + className + "] must be an instance of " + type;
}
throw new IllegalArgumentException(result);
}
private static void assignableCheckFailed(Class<?> superType, @Nullable Class<?> subType, @Nullable String msg) {
String result = "";
boolean defaultMessage = true;
if (StringUtils.hasLength(msg)) {
if (endsWithSeparator(msg)) {
result = msg + " ";
} else {
result = messageWithTypeName(msg, subType);
defaultMessage = false;
}
}
if (defaultMessage) {
result = result + subType + " is not assignable to " + superType;
}
throw new IllegalArgumentException(result);
}
private static boolean endsWithSeparator(String msg) {
return msg.endsWith(":") || msg.endsWith(";") || msg.endsWith(",") || msg.endsWith(".");
}
private static String messageWithTypeName(String msg, @Nullable Object typeName) {
return msg + (msg.endsWith(" ") ? "" : ": ") + typeName;
}
@Nullable
private static String nullSafeGet(@Nullable Supplier<String> messageSupplier) {
return messageSupplier != null ? (String)messageSupplier.get() : null;
}
}
=
=
=
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.core.env;
import java.security.AccessControlException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.SpringProperties;
import org.springframework.core.convert.support.ConfigurableConversionService;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
public abstract class AbstractEnvironment implements ConfigurableEnvironment {
public static final String IGNORE_GETENV_PROPERTY_NAME = "spring.getenv.ignore";
public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.profiles.active";
public static final String DEFAULT_PROFILES_PROPERTY_NAME = "spring.profiles.default";
protected static final String RESERVED_DEFAULT_PROFILE_NAME = "default";
protected final Log logger = LogFactory.getLog(this.getClass());
private final Set<String> activeProfiles = new LinkedHashSet();
private final Set<String> defaultProfiles = new LinkedHashSet(this.getReservedDefaultProfiles());
private final MutablePropertySources propertySources = new MutablePropertySources();
//配置文件助手
private final ConfigurablePropertyResolver propertyResolver;
public AbstractEnvironment() {
this.propertyResolver = new PropertySourcesPropertyResolver(this.propertySources);
this.customizePropertySources(this.propertySources);
}
protected void customizePropertySources(MutablePropertySources propertySources) {
}
protected Set<String> getReservedDefaultProfiles() {
return Collections.singleton("default");
}
public String[] getActiveProfiles() {
return StringUtils.toStringArray(this.doGetActiveProfiles());
}
protected Set<String> doGetActiveProfiles() {
Set var1 = this.activeProfiles;
synchronized(this.activeProfiles) {
if (this.activeProfiles.isEmpty()) {
String profiles = this.getProperty("spring.profiles.active");
if (StringUtils.hasText(profiles)) {
this.setActiveProfiles(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(profiles)));
}
}
return this.activeProfiles;
}
}
public void setActiveProfiles(String... profiles) {
Assert.notNull(profiles, "Profile array must not be null");
if (this.logger.isDebugEnabled()) {
this.logger.debug("Activating profiles " + Arrays.asList(profiles));
}
Set var2 = this.activeProfiles;
synchronized(this.activeProfiles) {
this.activeProfiles.clear();
String[] var3 = profiles;
int var4 = profiles.length;
for(int var5 = 0; var5 < var4; ++var5) {
String profile = var3[var5];
this.validateProfile(profile);
this.activeProfiles.add(profile);
}
}
}
public void addActiveProfile(String profile) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Activating profile '" + profile + "'");
}
this.validateProfile(profile);
this.doGetActiveProfiles();
Set var2 = this.activeProfiles;
synchronized(this.activeProfiles) {
this.activeProfiles.add(profile);
}
}
public String[] getDefaultProfiles() {
return StringUtils.toStringArray(this.doGetDefaultProfiles());
}
protected Set<String> doGetDefaultProfiles() {
Set var1 = this.defaultProfiles;
synchronized(this.defaultProfiles) {
if (this.defaultProfiles.equals(this.getReservedDefaultProfiles())) {
String profiles = this.getProperty("spring.profiles.default");
if (StringUtils.hasText(profiles)) {
this.setDefaultProfiles(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(profiles)));
}
}
return this.defaultProfiles;
}
}
public void setDefaultProfiles(String... profiles) {
Assert.notNull(profiles, "Profile array must not be null");
Set var2 = this.defaultProfiles;
synchronized(this.defaultProfiles) {
this.defaultProfiles.clear();
String[] var3 = profiles;
int var4 = profiles.length;
for(int var5 = 0; var5 < var4; ++var5) {
String profile = var3[var5];
this.validateProfile(profile);
this.defaultProfiles.add(profile);
}
}
}
/** @deprecated */
@Deprecated
public boolean acceptsProfiles(String... profiles) {
Assert.notEmpty(profiles, "Must specify at least one profile");
String[] var2 = profiles;
int var3 = profiles.length;
for(int var4 = 0; var4 < var3; ++var4) {
String profile = var2[var4];
if (StringUtils.hasLength(profile) && profile.charAt(0) == '!') {
if (!this.isProfileActive(profile.substring(1))) {
return true;
}
} else if (this.isProfileActive(profile)) {
return true;
}
}
return false;
}
public boolean acceptsProfiles(Profiles profiles) {
Assert.notNull(profiles, "Profiles must not be null");
return profiles.matches(this::isProfileActive);
}
protected boolean isProfileActive(String profile) {
this.validateProfile(profile);
Set<String> currentActiveProfiles = this.doGetActiveProfiles();
return currentActiveProfiles.contains(profile) || currentActiveProfiles.isEmpty() && this.doGetDefaultProfiles().contains(profile);
}
protected void validateProfile(String profile) {
if (!StringUtils.hasText(profile)) {
throw new IllegalArgumentException("Invalid profile [" + profile + "]: must contain text");
} else if (profile.charAt(0) == '!') {
throw new IllegalArgumentException("Invalid profile [" + profile + "]: must not begin with ! operator");
}
}
public MutablePropertySources getPropertySources() {
return this.propertySources;
}
public Map<String, Object> getSystemProperties() {
try {
return System.getProperties();
} catch (AccessControlException var2) {
return new ReadOnlySystemAttributesMap() {
@Nullable
protected String getSystemAttribute(String attributeName) {
try {
return System.getProperty(attributeName);
} catch (AccessControlException var3) {
if (AbstractEnvironment.this.logger.isInfoEnabled()) {
AbstractEnvironment.this.logger.info("Caught AccessControlException when accessing system property '" + attributeName + "'; its value will be returned [null]. Reason: " + var3.getMessage());
}
return null;
}
}
};
}
}
public Map<String, Object> getSystemEnvironment() {
if (this.suppressGetenvAccess()) {
return Collections.emptyMap();
} else {
try {
return System.getenv();
} catch (AccessControlException var2) {
return new ReadOnlySystemAttributesMap() {
@Nullable
protected String getSystemAttribute(String attributeName) {
try {
return System.getenv(attributeName);
} catch (AccessControlException var3) {
if (AbstractEnvironment.this.logger.isInfoEnabled()) {
AbstractEnvironment.this.logger.info("Caught AccessControlException when accessing system environment variable '" + attributeName + "'; its value will be returned [null]. Reason: " + var3.getMessage());
}
return null;
}
}
};
}
}
}
protected boolean suppressGetenvAccess() {
return SpringProperties.getFlag("spring.getenv.ignore");
}
public void merge(ConfigurableEnvironment parent) {
Iterator var2 = parent.getPropertySources().iterator();
while(var2.hasNext()) {
PropertySource<?> ps = (PropertySource)var2.next();
if (!this.propertySources.contains(ps.getName())) {
this.propertySources.addLast(ps);
}
}
String[] parentActiveProfiles = parent.getActiveProfiles();
if (!ObjectUtils.isEmpty(parentActiveProfiles)) {
Set var13 = this.activeProfiles;
synchronized(this.activeProfiles) {
Collections.addAll(this.activeProfiles, parentActiveProfiles);
}
}
String[] parentDefaultProfiles = parent.getDefaultProfiles();
if (!ObjectUtils.isEmpty(parentDefaultProfiles)) {
Set var4 = this.defaultProfiles;
synchronized(this.defaultProfiles) {
this.defaultProfiles.remove("default");
String[] var5 = parentDefaultProfiles;
int var6 = parentDefaultProfiles.length;
for(int var7 = 0; var7 < var6; ++var7) {
String profile = var5[var7];
this.defaultProfiles.add(profile);
}
}
}
}
public ConfigurableConversionService getConversionService() {
return this.propertyResolver.getConversionService();
}
public void setConversionService(ConfigurableConversionService conversionService) {
this.propertyResolver.setConversionService(conversionService);
}
public void setPlaceholderPrefix(String placeholderPrefix) {
this.propertyResolver.setPlaceholderPrefix(placeholderPrefix);
}
public void setPlaceholderSuffix(String placeholderSuffix) {
this.propertyResolver.setPlaceholderSuffix(placeholderSuffix);
}
public void setValueSeparator(@Nullable String valueSeparator) {
this.propertyResolver.setValueSeparator(valueSeparator);
}
public void setIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNestedPlaceholders) {
this.propertyResolver.setIgnoreUnresolvableNestedPlaceholders(ignoreUnresolvableNestedPlaceholders);
}
public void setRequiredProperties(String... requiredProperties) {
this.propertyResolver.setRequiredProperties(requiredProperties);
}
public void validateRequiredProperties() throws MissingRequiredPropertiesException {
this.propertyResolver.validateRequiredProperties();
}
public boolean containsProperty(String key) {
return this.propertyResolver.containsProperty(key);
}
@Nullable
public String getProperty(String key) {
return this.propertyResolver.getProperty(key);
}
public String getProperty(String key, String defaultValue) {
return this.propertyResolver.getProperty(key, defaultValue);
}
@Nullable
public <T> T getProperty(String key, Class<T> targetType) {
return this.propertyResolver.getProperty(key, targetType);
}
public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
return this.propertyResolver.getProperty(key, targetType, defaultValue);
}
public String getRequiredProperty(String key) throws IllegalStateException {
return this.propertyResolver.getRequiredProperty(key);
}
public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException {
return this.propertyResolver.getRequiredProperty(key, targetType);
}
public String resolvePlaceholders(String text) {
return this.propertyResolver.resolvePlaceholders(text);
}
/*
* text -> UserDao.xml
* 构造配置文件助手 主要存储一些配置文件的属性 如final 等
*/
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
return this.propertyResolver.resolveRequiredPlaceholders(text);
}
public String toString() {
return this.getClass().getSimpleName() + " {activeProfiles=" + this.activeProfiles + ", defaultProfiles=" + this.defaultProfiles + ", propertySources=" + this.propertySources + "}";
}
}
=
=
=
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.core.env;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.ConfigurableConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
public abstract class AbstractPropertyResolver implements ConfigurablePropertyResolver {
protected final Log logger = LogFactory.getLog(this.getClass());
@Nullable
private volatile ConfigurableConversionService conversionService;
@Nullable
private PropertyPlaceholderHelper nonStrictHelper;
@Nullable
private PropertyPlaceholderHelper strictHelper;
private boolean ignoreUnresolvableNestedPlaceholders = false;
private String placeholderPrefix = "${";
private String placeholderSuffix = "}";
@Nullable
private String valueSeparator = ":";
private final Set<String> requiredProperties = new LinkedHashSet();
public AbstractPropertyResolver() {
}
public ConfigurableConversionService getConversionService() {
ConfigurableConversionService cs = this.conversionService;
if (cs == null) {
synchronized(this) {
cs = this.conversionService;
if (cs == null) {
cs = new DefaultConversionService();
this.conversionService = (ConfigurableConversionService)cs;
}
}
}
return (ConfigurableConversionService)cs;
}
public void setConversionService(ConfigurableConversionService conversionService) {
Assert.notNull(conversionService, "ConversionService must not be null");
this.conversionService = conversionService;
}
public void setPlaceholderPrefix(String placeholderPrefix) {
Assert.notNull(placeholderPrefix, "'placeholderPrefix' must not be null");
this.placeholderPrefix = placeholderPrefix;
}
public void setPlaceholderSuffix(String placeholderSuffix) {
Assert.notNull(placeholderSuffix, "'placeholderSuffix' must not be null");
this.placeholderSuffix = placeholderSuffix;
}
public void setValueSeparator(@Nullable String valueSeparator) {
this.valueSeparator = valueSeparator;
}
public void setIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNestedPlaceholders) {
this.ignoreUnresolvableNestedPlaceholders = ignoreUnresolvableNestedPlaceholders;
}
public void setRequiredProperties(String... requiredProperties) {
Collections.addAll(this.requiredProperties, requiredProperties);
}
public void validateRequiredProperties() {
MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException();
Iterator var2 = this.requiredProperties.iterator();
while(var2.hasNext()) {
String key = (String)var2.next();
if (this.getProperty(key) == null) {
ex.addMissingRequiredProperty(key);
}
}
if (!ex.getMissingRequiredProperties().isEmpty()) {
throw ex;
}
}
public boolean containsProperty(String key) {
return this.getProperty(key) != null;
}
@Nullable
public String getProperty(String key) {
return (String)this.getProperty(key, String.class);
}
public String getProperty(String key, String defaultValue) {
String value = this.getProperty(key);
return value != null ? value : defaultValue;
}
public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
T value = this.getProperty(key, targetType);
return value != null ? value : defaultValue;
}
public String getRequiredProperty(String key) throws IllegalStateException {
String value = this.getProperty(key);
if (value == null) {
throw new IllegalStateException("Required key '" + key + "' not found");
} else {
return value;
}
}
public <T> T getRequiredProperty(String key, Class<T> valueType) throws IllegalStateException {
T value = this.getProperty(key, valueType);
if (value == null) {
throw new IllegalStateException("Required key '" + key + "' not found");
} else {
return value;
}
}
public String resolvePlaceholders(String text) {
if (this.nonStrictHelper == null) {
this.nonStrictHelper = this.createPlaceholderHelper(true);
}
return this.doResolvePlaceholders(text, this.nonStrictHelper);
}
/*
*构建严格的属性助手 指我们的 Bean
*
*/
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
//如果助手为空那么我们就会 创建一个助手保存我们 bean 的属性
if (this.strictHelper == null) {
this.strictHelper = this.createPlaceholderHelper(false);
}
return this.doResolvePlaceholders(text, this.strictHelper);
}
protected String resolveNestedPlaceholders(String value) {
return this.ignoreUnresolvableNestedPlaceholders ? this.resolvePlaceholders(value) : this.resolveRequiredPlaceholders(value);
}
/*
* 创建助手
* this.placeholderPrefix -> "${"
* this.placeholderSuffix -> "}"
* this.valueSeparator -> ":"
* ignoreUnresolvablePlaceholders -> false
*/
private PropertyPlaceholderHelper createPlaceholderHelper(boolean ignoreUnresolvablePlaceholders) {
return new PropertyPlaceholderHelper(this.placeholderPrefix, this.placeholderSuffix, this.valueSeparator, ignoreUnresolvablePlaceholders);
}
private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) {
return helper.replacePlaceholders(text, this::getPropertyAsRawString);
}
@Nullable
protected <T> T convertValueIfNecessary(Object value, @Nullable Class<T> targetType) {
if (targetType == null) {
return value;
} else {
ConversionService conversionServiceToUse = this.conversionService;
if (conversionServiceToUse == null) {
if (ClassUtils.isAssignableValue(targetType, value)) {
return value;
}
conversionServiceToUse = DefaultConversionService.getSharedInstance();
}
return ((ConversionService)conversionServiceToUse).convert(value, targetType);
}
}
@Nullable
protected abstract String getPropertyAsRawString(String var1);
}
=
=
=
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.util;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.lang.Nullable;
public class PropertyPlaceholderHelper {
private static final Log logger = LogFactory.getLog(PropertyPlaceholderHelper.class);
private static final Map<String, String> wellKnownSimplePrefixes = new HashMap(4);
private final String placeholderPrefix;
private final String placeholderSuffix;
private final String simplePrefix;
@Nullable
private final String valueSeparator;
private final boolean ignoreUnresolvablePlaceholders;
public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix) {
this(placeholderPrefix, placeholderSuffix, (String)null, true);
}
public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix, @Nullable String valueSeparator, boolean ignoreUnresolvablePlaceholders) {
Assert.notNull(placeholderPrefix, "'placeholderPrefix' must not be null");
Assert.notNull(placeholderSuffix, "'placeholderSuffix' must not be null");
this.placeholderPrefix = placeholderPrefix;
this.placeholderSuffix = placeholderSuffix;
String simplePrefixForSuffix = (String)wellKnownSimplePrefixes.get(this.placeholderSuffix);
if (simplePrefixForSuffix != null && this.placeholderPrefix.endsWith(simplePrefixForSuffix)) {
this.simplePrefix = simplePrefixForSuffix;
} else {
this.simplePrefix = this.placeholderPrefix;
}
this.valueSeparator = valueSeparator;
this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
}
public String replacePlaceholders(String value, Properties properties) {
Assert.notNull(properties, "'properties' must not be null");
properties.getClass();
return this.replacePlaceholders(value, properties::getProperty);
}
/*
* 判断是否为空,为空抛出异常信息
*/
public String replacePlaceholders(String value, PropertyPlaceholderHelper.PlaceholderResolver placeholderResolver) {
//判断是否为空,为空抛出异常信息
Assert.notNull(value, "'value' must not be null");
return this.parseStringValue(value, placeholderResolver, (Set)null);
}
protected String parseStringValue(String value, PropertyPlaceholderHelper.PlaceholderResolver placeholderResolver, @Nullable Set<String> visitedPlaceholders) {
int startIndex = value.indexOf(this.placeholderPrefix);
if (startIndex == -1) {
return value;
} else {
StringBuilder result = new StringBuilder(value);
while(startIndex != -1) {
int endIndex = this.findPlaceholderEndIndex(result, startIndex);
if (endIndex != -1) {
String placeholder = result.substring(startIndex + this.placeholderPrefix.length(), endIndex);
String originalPlaceholder = placeholder;
if (visitedPlaceholders == null) {
visitedPlaceholders = new HashSet(4);
}
if (!((Set)visitedPlaceholders).add(placeholder)) {
throw new IllegalArgumentException("Circular placeholder reference '" + placeholder + "' in property definitions");
}
placeholder = this.parseStringValue(placeholder, placeholderResolver, (Set)visitedPlaceholders);
String propVal = placeholderResolver.resolvePlaceholder(placeholder);
if (propVal == null && this.valueSeparator != null) {
int separatorIndex = placeholder.indexOf(this.valueSeparator);
if (separatorIndex != -1) {
String actualPlaceholder = placeholder.substring(0, separatorIndex);
String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
if (propVal == null) {
propVal = defaultValue;
}
}
}
if (propVal != null) {
propVal = this.parseStringValue(propVal, placeholderResolver, (Set)visitedPlaceholders);
result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
if (logger.isTraceEnabled()) {
logger.trace("Resolved placeholder '" + placeholder + "'");
}
startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length());
} else {
if (!this.ignoreUnresolvablePlaceholders) {
throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "' in value \"" + value + "\"");
}
startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
}
((Set)visitedPlaceholders).remove(originalPlaceholder);
} else {
startIndex = -1;
}
}
return result.toString();
}
}
private int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
int index = startIndex + this.placeholderPrefix.length();
int withinNestedPlaceholder = 0;
while(index < buf.length()) {
if (StringUtils.substringMatch(buf, index, this.placeholderSuffix)) {
if (withinNestedPlaceholder <= 0) {
return index;
}
--withinNestedPlaceholder;
index += this.placeholderSuffix.length();
} else if (StringUtils.substringMatch(buf, index, this.simplePrefix)) {
++withinNestedPlaceholder;
index += this.simplePrefix.length();
} else {
++index;
}
}
return -1;
}
/*
* 通过静态方法 给集合赋值
*
*/
static {
wellKnownSimplePrefixes.put("}", "{");
wellKnownSimplePrefixes.put("]", "[");
wellKnownSimplePrefixes.put(")", "(");
}
@FunctionalInterface
public interface PlaceholderResolver {
@Nullable
String resolvePlaceholder(String var1);
}
}
刷新方法
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.context.support;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.CachedIntrospectionResults;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.support.ResourceEditorRegistrar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.HierarchicalMessageSource;
import org.springframework.context.LifecycleProcessor;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.context.weaving.LoadTimeWeaverAware;
import org.springframework.context.weaving.LoadTimeWeaverAwareProcessor;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringValueResolver;
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
public static final String MESSAGE_SOURCE_BEAN_NAME = "messageSource";
public static final String LIFECYCLE_PROCESSOR_BEAN_NAME = "lifecycleProcessor";
public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
protected final Log logger;
private String id;
private String displayName;
@Nullable
private ApplicationContext parent;
@Nullable
private ConfigurableEnvironment environment;
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors;
private long startupDate;
private final AtomicBoolean active;
private final AtomicBoolean closed;
private final Object startupShutdownMonitor;
@Nullable
private Thread shutdownHook;
private ResourcePatternResolver resourcePatternResolver;
@Nullable
private LifecycleProcessor lifecycleProcessor;
@Nullable
private MessageSource messageSource;
@Nullable
private ApplicationEventMulticaster applicationEventMulticaster;
private final Set<ApplicationListener<?>> applicationListeners;
@Nullable
private Set<ApplicationListener<?>> earlyApplicationListeners;
@Nullable
private Set<ApplicationEvent> earlyApplicationEvents;
public AbstractApplicationContext() {
this.logger = LogFactory.getLog(this.getClass());
this.id = ObjectUtils.identityToString(this);
this.displayName = ObjectUtils.identityToString(this);
this.beanFactoryPostProcessors = new ArrayList();
this.active = new AtomicBoolean();
this.closed = new AtomicBoolean();
this.startupShutdownMonitor = new Object();
this.applicationListeners = new LinkedHashSet();
this.resourcePatternResolver = this.getResourcePatternResolver();
}
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
this.setParent(parent);
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return this.id;
}
public String getApplicationName() {
return "";
}
public void setDisplayName(String displayName) {
Assert.hasLength(displayName, "Display name must not be empty");
this.displayName = displayName;
}
public String getDisplayName() {
return this.displayName;
}
@Nullable
public ApplicationContext getParent() {
return this.parent;
}
public void setEnvironment(ConfigurableEnvironment environment) {
this.environment = environment;
}
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
this.environment = this.createEnvironment();
}
return this.environment;
}
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}
public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException {
return this.getBeanFactory();
}
public long getStartupDate() {
return this.startupDate;
}
public void publishEvent(ApplicationEvent event) {
this.publishEvent(event, (ResolvableType)null);
}
public void publishEvent(Object event) {
this.publishEvent(event, (ResolvableType)null);
}
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
Assert.notNull(event, "Event must not be null");
Object applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent)event;
} else {
applicationEvent = new PayloadApplicationEvent(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent)applicationEvent).getResolvableType();
}
}
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
} else {
this.getApplicationEventMulticaster().multicastEvent((ApplicationEvent)applicationEvent, eventType);
}
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext) {
((AbstractApplicationContext)this.parent).publishEvent(event, eventType);
} else {
this.parent.publishEvent(event);
}
}
}
ApplicationEventMulticaster getApplicationEventMulticaster() throws IllegalStateException {
if (this.applicationEventMulticaster == null) {
throw new IllegalStateException("ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: " + this);
} else {
return this.applicationEventMulticaster;
}
}
LifecycleProcessor getLifecycleProcessor() throws IllegalStateException {
if (this.lifecycleProcessor == null) {
throw new IllegalStateException("LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: " + this);
} else {
return this.lifecycleProcessor;
}
}
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
public void setParent(@Nullable ApplicationContext parent) {
this.parent = parent;
if (parent != null) {
Environment parentEnvironment = parent.getEnvironment();
if (parentEnvironment instanceof ConfigurableEnvironment) {
this.getEnvironment().merge((ConfigurableEnvironment)parentEnvironment);
}
}
}
public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) {
Assert.notNull(postProcessor, "BeanFactoryPostProcessor must not be null");
this.beanFactoryPostProcessors.add(postProcessor);
}
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return this.beanFactoryPostProcessors;
}
public void addApplicationListener(ApplicationListener<?> listener) {
Assert.notNull(listener, "ApplicationListener must not be null");
if (this.applicationEventMulticaster != null) {
this.applicationEventMulticaster.addApplicationListener(listener);
}
this.applicationListeners.add(listener);
}
public Collection<ApplicationListener<?>> getApplicationListeners() {
return this.applicationListeners;
}
/*
通过反射把bean封装在map集合中
*/
public void refresh() throws BeansException, IllegalStateException {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (this.logger.isDebugEnabled()) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Refreshing " + this);
} else {
this.logger.debug("Refreshing " + this.getDisplayName());
}
}
this.initPropertySources();
this.getEnvironment().validateRequiredProperties();
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet(this.applicationListeners);
} else {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
this.earlyApplicationEvents = new LinkedHashSet();
}
protected void initPropertySources() {
}
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
this.refreshBeanFactory();
return this.getBeanFactory();
}
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.setBeanClassLoader(this.getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment()));
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
if (beanFactory.containsBean("loadTimeWeaver")) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
if (!beanFactory.containsLocalBean("environment")) {
beanFactory.registerSingleton("environment", this.getEnvironment());
}
if (!beanFactory.containsLocalBean("systemProperties")) {
beanFactory.registerSingleton("systemProperties", this.getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean("systemEnvironment")) {
beanFactory.registerSingleton("systemEnvironment", this.getEnvironment().getSystemEnvironment());
}
}
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, this.getBeanFactoryPostProcessors());
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean("loadTimeWeaver")) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
if (beanFactory.containsLocalBean("messageSource")) {
this.messageSource = (MessageSource)beanFactory.getBean("messageSource", MessageSource.class);
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource)this.messageSource;
if (hms.getParentMessageSource() == null) {
hms.setParentMessageSource(this.getInternalParentMessageSource());
}
}
if (this.logger.isTraceEnabled()) {
this.logger.trace("Using MessageSource [" + this.messageSource + "]");
}
} else {
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(this.getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton("messageSource", this.messageSource);
if (this.logger.isTraceEnabled()) {
this.logger.trace("No 'messageSource' bean, using [" + this.messageSource + "]");
}
}
}
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
if (beanFactory.containsLocalBean("applicationEventMulticaster")) {
this.applicationEventMulticaster = (ApplicationEventMulticaster)beanFactory.getBean("applicationEventMulticaster", ApplicationEventMulticaster.class);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
} else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton("applicationEventMulticaster", this.applicationEventMulticaster);
if (this.logger.isTraceEnabled()) {
this.logger.trace("No 'applicationEventMulticaster' bean, using [" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
if (beanFactory.containsLocalBean("lifecycleProcessor")) {
this.lifecycleProcessor = (LifecycleProcessor)beanFactory.getBean("lifecycleProcessor", LifecycleProcessor.class);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
} else {
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton("lifecycleProcessor", this.lifecycleProcessor);
if (this.logger.isTraceEnabled()) {
this.logger.trace("No 'lifecycleProcessor' bean, using [" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
protected void onRefresh() throws BeansException {
}
protected void registerListeners() {
Iterator var1 = this.getApplicationListeners().iterator();
while(var1.hasNext()) {
ApplicationListener<?> listener = (ApplicationListener)var1.next();
this.getApplicationEventMulticaster().addApplicationListener(listener);
}
String[] listenerBeanNames = this.getBeanNamesForType(ApplicationListener.class, true, false);
String[] var7 = listenerBeanNames;
int var3 = listenerBeanNames.length;
for(int var4 = 0; var4 < var3; ++var4) {
String listenerBeanName = var7[var4];
this.getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
Iterator var9 = earlyEventsToProcess.iterator();
while(var9.hasNext()) {
ApplicationEvent earlyEvent = (ApplicationEvent)var9.next();
this.getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
if (beanFactory.containsBean("conversionService") && beanFactory.isTypeMatch("conversionService", ConversionService.class)) {
beanFactory.setConversionService((ConversionService)beanFactory.getBean("conversionService", ConversionService.class));
}
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver((strVal) -> {
return this.getEnvironment().resolvePlaceholders(strVal);
});
}
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
String[] var3 = weaverAwareNames;
int var4 = weaverAwareNames.length;
for(int var5 = 0; var5 < var4; ++var5) {
String weaverAwareName = var3[var5];
this.getBean(weaverAwareName);
}
beanFactory.setTempClassLoader((ClassLoader)null);
beanFactory.freezeConfiguration();
beanFactory.preInstantiateSingletons();
}
protected void finishRefresh() {
this.clearResourceCaches();
this.initLifecycleProcessor();
this.getLifecycleProcessor().onRefresh();
this.publishEvent((ApplicationEvent)(new ContextRefreshedEvent(this)));
LiveBeansView.registerApplicationContext(this);
}
protected void cancelRefresh(BeansException ex) {
this.active.set(false);
}
protected void resetCommonCaches() {
ReflectionUtils.clearCache();
AnnotationUtils.clearCache();
ResolvableType.clearCache();
CachedIntrospectionResults.clearClassLoader(this.getClassLoader());
}
public void registerShutdownHook() {
if (this.shutdownHook == null) {
this.shutdownHook = new Thread("SpringContextShutdownHook") {
public void run() {
synchronized(AbstractApplicationContext.this.startupShutdownMonitor) {
AbstractApplicationContext.this.doClose();
}
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
}
/** @deprecated */
@Deprecated
public void destroy() {
this.close();
}
public void close() {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
this.doClose();
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
} catch (IllegalStateException var4) {
;
}
}
}
}
protected void doClose() {
if (this.active.get() && this.closed.compareAndSet(false, true)) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Closing " + this);
}
LiveBeansView.unregisterApplicationContext(this);
try {
this.publishEvent((ApplicationEvent)(new ContextClosedEvent(this)));
} catch (Throwable var3) {
this.logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", var3);
}
if (this.lifecycleProcessor != null) {
try {
this.lifecycleProcessor.onClose();
} catch (Throwable var2) {
this.logger.warn("Exception thrown from LifecycleProcessor on context close", var2);
}
}
this.destroyBeans();
this.closeBeanFactory();
this.onClose();
if (this.earlyApplicationListeners != null) {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
this.active.set(false);
}
}
protected void destroyBeans() {
this.getBeanFactory().destroySingletons();
}
protected void onClose() {
}
public boolean isActive() {
return this.active.get();
}
protected void assertBeanFactoryActive() {
if (!this.active.get()) {
if (this.closed.get()) {
throw new IllegalStateException(this.getDisplayName() + " has been closed already");
} else {
throw new IllegalStateException(this.getDisplayName() + " has not been refreshed yet");
}
}
}
public Object getBean(String name) throws BeansException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBean(name);
}
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBean(name, requiredType);
}
public Object getBean(String name, Object... args) throws BeansException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBean(name, args);
}
public <T> T getBean(Class<T> requiredType) throws BeansException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBean(requiredType);
}
public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBean(requiredType, args);
}
public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBeanProvider(requiredType);
}
public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType) {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBeanProvider(requiredType);
}
public boolean containsBean(String name) {
return this.getBeanFactory().containsBean(name);
}
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
this.assertBeanFactoryActive();
return this.getBeanFactory().isSingleton(name);
}
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
this.assertBeanFactoryActive();
return this.getBeanFactory().isPrototype(name);
}
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
this.assertBeanFactoryActive();
return this.getBeanFactory().isTypeMatch(name, typeToMatch);
}
public boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException {
this.assertBeanFactoryActive();
return this.getBeanFactory().isTypeMatch(name, typeToMatch);
}
@Nullable
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getType(name);
}
@Nullable
public Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getType(name, allowFactoryBeanInit);
}
public String[] getAliases(String name) {
return this.getBeanFactory().getAliases(name);
}
public boolean containsBeanDefinition(String beanName) {
return this.getBeanFactory().containsBeanDefinition(beanName);
}
public int getBeanDefinitionCount() {
return this.getBeanFactory().getBeanDefinitionCount();
}
public String[] getBeanDefinitionNames() {
return this.getBeanFactory().getBeanDefinitionNames();
}
public String[] getBeanNamesForType(ResolvableType type) {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBeanNamesForType(type);
}
public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
}
public String[] getBeanNamesForType(@Nullable Class<?> type) {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBeanNamesForType(type);
}
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
}
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBeansOfType(type);
}
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBeansOfType(type, includeNonSingletons, allowEagerInit);
}
public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBeanNamesForAnnotation(annotationType);
}
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBeansWithAnnotation(annotationType);
}
@Nullable
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws NoSuchBeanDefinitionException {
this.assertBeanFactoryActive();
return this.getBeanFactory().findAnnotationOnBean(beanName, annotationType);
}
@Nullable
public BeanFactory getParentBeanFactory() {
return this.getParent();
}
public boolean containsLocalBean(String name) {
return this.getBeanFactory().containsLocalBean(name);
}
@Nullable
protected BeanFactory getInternalParentBeanFactory() {
return (BeanFactory)(this.getParent() instanceof ConfigurableApplicationContext ? ((ConfigurableApplicationContext)this.getParent()).getBeanFactory() : this.getParent());
}
public String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale) {
return this.getMessageSource().getMessage(code, args, defaultMessage, locale);
}
public String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException {
return this.getMessageSource().getMessage(code, args, locale);
}
public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
return this.getMessageSource().getMessage(resolvable, locale);
}
private MessageSource getMessageSource() throws IllegalStateException {
if (this.messageSource == null) {
throw new IllegalStateException("MessageSource not initialized - call 'refresh' before accessing messages via the context: " + this);
} else {
return this.messageSource;
}
}
@Nullable
protected MessageSource getInternalParentMessageSource() {
return (MessageSource)(this.getParent() instanceof AbstractApplicationContext ? ((AbstractApplicationContext)this.getParent()).messageSource : this.getParent());
}
public Resource[] getResources(String locationPattern) throws IOException {
return this.resourcePatternResolver.getResources(locationPattern);
}
public void start() {
this.getLifecycleProcessor().start();
this.publishEvent((ApplicationEvent)(new ContextStartedEvent(this)));
}
public void stop() {
this.getLifecycleProcessor().stop();
this.publishEvent((ApplicationEvent)(new ContextStoppedEvent(this)));
}
public boolean isRunning() {
return this.lifecycleProcessor != null && this.lifecycleProcessor.isRunning();
}
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
protected abstract void closeBeanFactory();
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
public String toString() {
StringBuilder sb = new StringBuilder(this.getDisplayName());
sb.append(", started on ").append(new Date(this.getStartupDate()));
ApplicationContext parent = this.getParent();
if (parent != null) {
sb.append(", parent: ").append(parent.getDisplayName());
}
return sb.toString();
}
static {
ContextClosedEvent.class.getName();
}
}
总结: (比较简洁)
1.ApplicationContext通过一系列判断,判断出我们传入的对象不为空
2.然后通过我们的文件 获取 文件的真实执行路径
3.然后通过工厂模式 通过反射将我们封装到xml里的文件通过反射一个一个解析 出来,放在以Object的形式放在Map集合中
4.通过getBean方法,因为getbean要传入需要解析的文件类,
5.在进行一系列的判断,判断我们传入的类是否存在
6.通过这个类反射得到我们想要的Bean实例,传给我们的文件