工厂模式
1、new对象
public class UserDao {
public void test(){
System
.out
.println("test()方法调用");
}
}
public class UserService {
public static void main(String
[] args
) {
UserDao userDao
= new UserDao();
userDao
.test();
}
}
两个对象之间耦合大,UserDao改动,调用的地方都需要改动。使用工厂模式创建对象,减小UserDao和 UserService 的耦合。
2、工厂创建对象
Map作为容器存放各种Bean,key为工厂中的唯一标识,value为创建的对象static静态代码块中反射实例化对象存入map中
public class Factory {
private static Map
<String, Object> map
= new HashMap<String, Object>();
static {
try {
Constructor
<UserDao> constructor
= UserDao
.class.getDeclaredConstructor(null
);
UserDao userDao
= constructor
.newInstance();
map
.put("userDao",userDao
);
} catch (Exception e
) {
e
.printStackTrace();
}
}
public Object
getBean(String beanName
){
return map
.get(beanName
);
}
}
创建需要的工厂给定id拿到对应的Bean
public class UserService {
public static void main(String
[] args
) {
Factory factory
= new Factory();
UserDao userDao
= (UserDao
) factory
.getBean("userDao");
userDao
.test();
}
}
3、配置文件
工厂中创建大量的Bean,将Bean的Id和Bean对象都编写到代码中,不便修改
将对象ID和对象的包名和类名存入配置文件中方便对工厂中随意添加Bean信息
userDao=com.wdd.UserDao
public class Factory {
private static Map
<String, Object> map
= new HashMap<String, Object>();
private static String fileName
="bean";
static {
try {
ResourceBundle rb
= ResourceBundle
.getBundle(fileName
);
Enumeration
<String> keys
= rb
.getKeys();
while (keys
.hasMoreElements()){
String key
= keys
.nextElement();
String clazz
= rb
.getString(key
);
Class
<?> aClass
= Class
.forName(clazz
);
Constructor
<?> constructor
= aClass
.getDeclaredConstructor(null
);
Object instance
= constructor
.newInstance();
map
.put(key
,instance
);
}
} catch (Exception e
) {
e
.printStackTrace();
}
}
public Object
getBean(String beanName
){
return map
.get(beanName
);
}
}
IOC
控制反转:
是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫依赖查找(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。
对于UserService来说,获取UserDao对象可以通过两种方式获取。一种直接new对象主动获取,一种通过获得工厂传入对象id等待工厂提供对象。把创建对象的主动权交给工厂来控制叫控制反转
1、spring中的bean.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="spring.UserDao"/>
<bean id="userService" class="spring.UserService">
<property name="userDao" ref="userDao"/>
</bean>
</beans>
public class UserDao {
public void testDao(){
System
.out
.println("Dao的test()方法执行了。。。。");
}
}
public class UserService {
private UserDao userDao
;
public void setUserDao(UserDao userDao
) { this.userDao
= userDao
; }
public void testSrvvice(){
userDao
.testDao();
System
.out
.println("service的test()方法执行。。。。");
}
}
public static void main(String
[] args
) {
ApplicationContext ac
= new ClassPathXmlApplicationContext("bean.xml");
UserService userService
= ac
.getBean("userService", UserService
.class);
userService
.testSrvvice();
}
2、Spring的IOC
ClassPathXmlApplicationContext类
public ClassPathXmlApplicationContext(String configLocation
) throws BeansException
{
this(new String[]{configLocation
},
true,
(ApplicationContext
)null
);
}
-----------------
public ClassPathXmlApplicationContext(String
[] configLocations
, boolean refresh
, @Nullable ApplicationContext parent
) throws BeansException
{
super(parent
);
this.setConfigLocations(configLocations
);
if (refresh
) {
this.refresh();
}
}
AbstractApplicationContext类
public void refresh() throws BeansException
, IllegalStateException
{
synchronized (this.startupShutdownMonitor
) {
prepareRefresh();
ConfigurableListableBeanFactory beanFactory
= obtainFreshBeanFactory();
prepareBeanFactory(beanFactory
);
try {
postProcessBeanFactory(beanFactory
);
invokeBeanFactoryPostProcessors(beanFactory
);
registerBeanPostProcessors(beanFactory
);
initMessageSource();
initApplicationEventMulticaster();
onRefresh();
registerListeners();
finishBeanFactoryInitialization(beanFactory
);
finishRefresh();
}
catch (BeansException ex
) {
if (logger
.isWarnEnabled()) {
logger
.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex
);
}
destroyBeans();
cancelRefresh(ex
);
throw ex
;
}
finally {
resetCommonCaches();
}
}
}
prepareRefresh();
protected void prepareRefresh() {
this.startupDate
= System
.currentTimeMillis();
this.closed
.set(false);
this.active
.set(true);
......
initPropertySources();
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<>();
}
obtainFreshBeanFactory()
protected ConfigurableListableBeanFactory
obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
==============
protected final void refreshBeanFactory() throws BeansException
{
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory
= createBeanFactory();
beanFactory
.setSerializationId(getId());
customizeBeanFactory(beanFactory
);
loadBeanDefinitions(beanFactory
);
this.beanFactory
= beanFactory
;
}
catch (IOException ex
) {
throw new ApplicationContextException("I/O error parsing bean definition source for "
+ getDisplayName(), ex
);
}
}
prepareBeanFactory()
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory
) {
beanFactory
.setBeanClassLoader(getClassLoader());
。。。。。。
beanFactory
.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
。。。。。。
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));
}
postProcessBeanFactory(beanFactory)
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory
) {
}
invokeBeanFactoryPostProcessors(beanFactory)
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory
) {
PostProcessorRegistrationDelegate
.invokeBeanFactoryPostProcessors(beanFactory
, getBeanFactoryPostProcessors());
if (beanFactory
.getTempClassLoader() == null
&& beanFactory
.containsBean(LOAD_TIME_WEAVER_BEAN_NAME
)) {
beanFactory
.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory
));
beanFactory
.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory
.getBeanClassLoader()));
}
}
=========================
【PostProcessorRegistrationDelegate类】
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory
,
List
<BeanFactoryPostProcessor> beanFactoryPostProcessors
) {
Set
<String> processedBeans
= new HashSet<>();
if (beanFactory
instanceof BeanDefinitionRegistry) {
。。。。。。
}
List
<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors
= new ArrayList<>();
String
[] postProcessorNames
=beanFactory
.getBeanNamesForType(
BeanDefinitionRegistryPostProcessor
.class, true, false);
for (String ppName
: postProcessorNames
) {
if (beanFactory
.isTypeMatch(ppName
, PriorityOrdered
.class)) {
。。。。。。
}
}
sortPostProcessors(currentRegistryProcessors
, beanFactory
);
registryProcessors
.addAll(currentRegistryProcessors
);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors
, registry
);
currentRegistryProcessors
.clear();
postProcessorNames
= beanFactory
.getBeanNamesForType(
BeanDefinitionRegistryPostProcessor
.class, true, false);
for (String ppName
: postProcessorNames
) {
if (!processedBeans
.contains(ppName
)
&& beanFactory
.isTypeMatch(ppName
, Ordered
.class)) {
。。。。。。
}
}
sortPostProcessors(currentRegistryProcessors
, beanFactory
);
registryProcessors
.addAll(currentRegistryProcessors
);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors
, registry
);
currentRegistryProcessors
.clear();
boolean reiterate
= true;
while (reiterate
) {
reiterate
= false;
。。。。。。
}
invokeBeanFactoryPostProcessors(registryProcessors
, beanFactory
);
invokeBeanFactoryPostProcessors(regularPostProcessors
, beanFactory
);
}
else {
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors
, beanFactory
);
}
registerBeanPostProcessors(beanFactory);
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory
) {
PostProcessorRegistrationDelegate
.registerBeanPostProcessors(beanFactory
, this);
}
========
【PostProcessorRegistrationDelegate类】
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory
,
AbstractApplicationContext applicationContext
) {
String
[] postProcessorNames
= beanFactory
.getBeanNamesForType(
BeanPostProcessor
.class, true, false);
int beanProcessorTargetCount
= beanFactory
.getBeanPostProcessorCount() +
1 + postProcessorNames
.length
;
beanFactory
.addBeanPostProcessor(
new BeanPostProcessorChecker(beanFactory
, beanProcessorTargetCount
));
List
<BeanPostProcessor> priorityOrderedPostProcessors
= new ArrayList<>();
List
<BeanPostProcessor> internalPostProcessors
= new ArrayList<>();
List
<String> orderedPostProcessorNames
= new ArrayList<>();
List
<String> nonOrderedPostProcessorNames
= new ArrayList<>();
beanFactory
.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext
));
}
======
public String
[] getBeanNamesForType(@Nullable Class
<?> type
, boolean includeNonSingletons
, boolean allowEagerInit
) {
if (!isConfigurationFrozen() || type
== null
|| !allowEagerInit
) {
return doGetBeanNamesForType(
ResolvableType
.forRawClass(type
),
includeNonSingletons
,
allowEagerInit
);
}
。。。。。。
}
======
private String
[] doGetBeanNamesForType(ResolvableType type
, boolean includeNonSingletons
, boolean allowEagerInit
) {
List
<String> result
= new ArrayList<>();
for (String beanName
: this.beanDefinitionNames
) {
。。。。。。
}
for (String beanName
: this.manualSingletonNames
) {
。。。。。。
}
return StringUtils
.toStringArray(result
);
}
initMessageSource():国际化
initApplicationEventMulticaster():初始化事件广播器
onRefresh()
protected void onRefresh() throws BeansException
{
}
registerListeners();:注册所有的监听器
finishBeanFactoryInitialization(beanFactory)
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory
) {
。。。。。。
beanFactory
.preInstantiateSingletons();
}
public void preInstantiateSingletons() throws BeansException
{
List
<String> beanNames
= new ArrayList<>(this.beanDefinitionNames
);
for (String beanName
: beanNames
) {
RootBeanDefinition bd
= getMergedLocalBeanDefinition(beanName
);
if (!bd
.isAbstract() && bd
.isSingleton() && !bd
.isLazyInit()) {
if (isFactoryBean(beanName
)) {
。。。。。。
}
else {
getBean(beanName
);
}
}
}
for (String beanName
: beanNames
) {...}
}
===============
public Object
getBean(String name
) throws BeansException
{
return doGetBean(name
, null
, null
, false);
}
protected <T> T
doGetBean(
String name
, @Nullable Class
<T> requiredType
,
@Nullable Object
[] args
, boolean typeCheckOnly
)throws BeansException
{
if (mbd
.isSingleton()) {
sharedInstance
= getSingleton(beanName
, () -> {
。。。。。
return createBean(beanName
, mbd
, args
);
。。。。。。
});
bean
= getObjectForBeanInstance(sharedInstance
, name
, beanName
, mbd
);
}
return (T
) bean
;
}
protected Object
createBean(String beanName
,
RootBeanDefinition mbd
,
@Nullable Object
[] args
)throws BeanCreationException
{
......
try {
Object beanInstance
= doCreateBean(beanName
, mbdToUse
, args
);
return beanInstance
;
}
catch (...) {...}
}
protected Object
doCreateBean(String beanName
, RootBeanDefinition mbd
,
@Nullable Object
[] args
)throws BeanCreationException
{
BeanWrapper instanceWrapper
= null
;
if (mbd
.isSingleton()) {
instanceWrapper
= this.factoryBeanInstanceCache
.remove(beanName
);
}
if (instanceWrapper
== null
) {
instanceWrapper
= createBeanInstance(beanName
, mbd
, args
);
}
。。。
boolean earlySingletonExposure
= (mbd
.isSingleton() && this.allowCircularReferences
&&
isSingletonCurrentlyInCreation(beanName
));
if (earlySingletonExposure
) {
...
addSingletonFactory(beanName
, () -> getEarlyBeanReference(beanName
, mbd
, bean
));
}
Object exposedObject
= bean
;
try {
populateBean(beanName
, mbd
, instanceWrapper
);
exposedObject
= initializeBean(beanName
, exposedObject
, mbd
);
}
catch (Throwable ex
) {。。。
}
。。。。。。
return exposedObject
;
}
protected BeanWrapper
createBeanInstance(String beanName
, RootBeanDefinition mbd
, @Nullable Object
[] args
) {
Class
<?> beanClass
= resolveBeanClass(mbd
, beanName
);
if (beanClass
!= null
&& !Modifier
.isPublic(beanClass
.getModifiers()) &&
!mbd
.isNonPublicAccessAllowed()) {。。。。。。
}
。。。。。。
boolean resolved
= false;
boolean autowireNecessary
= false;
if (args
== null
) {。。。。。。
}
if (resolved
) {。。。。。。
}
Constructor
<?>[] ctors
= determineConstructorsFromBeanPostProcessors(beanClass
, beanName
);
if (ctors
!= null
|| mbd
.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR
||
mbd
.hasConstructorArgumentValues() || !ObjectUtils
.isEmpty(args
)) {
return autowireConstructor(beanName
, mbd
, ctors
, args
);
}
ctors
= mbd
.getPreferredConstructors();
if (ctors
!= null
) {
return autowireConstructor(beanName
, mbd
, ctors
, null
);
}
return instantiateBean(beanName
, mbd
);
}
实例化Bean
protected BeanWrapper
instantiateBean(String beanName
, RootBeanDefinition mbd
) {
try {
Object beanInstance
;
if (System
.getSecurityManager() != null
) {。。。
}
else {
beanInstance
= getInstantiationStrategy().instantiate(mbd
, beanName
, this);
}
}
catch (Throwable ex
) {。。。
}
}
public Object
instantiate(RootBeanDefinition bd
, @Nullable String beanName
, BeanFactory owner
) {
...
return BeanUtils
.instantiateClass(constructorToUse
);
...
}
public static <T> T
instantiateClass(Constructor
<T> ctor
,
Object
... args
) throws BeanInstantiationException
{
Assert
.notNull(ctor
, "Constructor must not be null");
try {
ReflectionUtils
.makeAccessible(ctor
);
if (KotlinDetector
.isKotlinReflectPresent() && KotlinDetector
.
isKotlinType(ctor
.getDeclaringClass())) {
return KotlinDelegate
.instantiateClass(ctor
, args
);
}
else {
Class
<?>[] parameterTypes
= ctor
.getParameterTypes();
...
return ctor
.newInstance(argsWithDefaultValues
);
}
}
catch (ex) {...}
}
初始化Bean
protected Object
initializeBean(String beanName
, Object bean
, @Nullable RootBeanDefinition mbd
) {
。。。
Object wrappedBean
= bean
;
if (mbd
== null
|| !mbd
.isSynthetic()) {
wrappedBean
= applyBeanPostProcessorsBeforeInitialization(wrappedBean
, beanName
);
}
try {
invokeInitMethods(beanName
, wrappedBean
, mbd
);
}
catch (Throwable ex
) {。。。
}
if (mbd
== null
|| !mbd
.isSynthetic()) {
wrappedBean
= applyBeanPostProcessorsAfterInitialization(wrappedBean
, beanName
);
}
return wrappedBean
;
}
public Object
applyBeanPostProcessorsBeforeInitialization(Object existingBean
, String beanName
)
throws BeansException
{
Object result
= existingBean
;
for (BeanPostProcessor processor
: getBeanPostProcessors()) {
Object current
= processor
.postProcessBeforeInitialization(result
, beanName
);
if (current
== null
) {
return result
;
}
result
= current
;
}
return result
;
}
public Object
applyBeanPostProcessorsAfterInitialization(Object existingBean
, String beanName
)
throws BeansException
{
Object result
= existingBean
;
for (BeanPostProcessor processor
: getBeanPostProcessors()) {
Object current
= processor
.postProcessAfterInitialization(result
, beanName
);
if (current
== null
) {
return result
;
}
result
= current
;
}
return result
;
}
3、Spring的AOP
public interface BeanPostProcessor {
default Object
postProcessBeforeInitialization(Object bean
,
String beanName
) throws BeansException
{
return bean
;
}
default Object
postProcessAfterInitialization(Object bean
,
String beanName
) throws BeansException
{
return bean
;
}
}
public Object
postProcessAfterInitialization(@Nullable Object bean
, String beanName
) {
if (bean
!= null
) {
Object cacheKey
= this.getCacheKey(bean
.getClass(), beanName
);
if (this.earlyProxyReferences
.remove(cacheKey
) != bean
) {
return this.wrapIfNecessary(bean
, beanName
, cacheKey
);
}
}
return bean
;
}
protected Object
wrapIfNecessary(Object bean
, String beanName
, Object cacheKey
) {
if (...) {...
} else if (...) {...
} else if (...) {...
if (...) {
Object proxy
= this.createProxy(bean
.getClass(),
beanName
,
specificInterceptors
,
new SingletonTargetSource(bean
));
this.proxyTypes
.put(cacheKey
, proxy
.getClass());
return proxy
;
} else {...}
} else {...}
}
protected Object
createProxy(Class
<?> beanClass
, @Nullable String beanName
, @Nullable Object
[] specificInterceptors
, TargetSource targetSource
) {
。。。。。。
return proxyFactory
.getProxy(this.getProxyClassLoader());
}
public Object
getProxy(@Nullable ClassLoader classLoader
) {
return this.createAopProxy().getProxy(classLoader
);
}
JDK
public Object
getProxy(@Nullable ClassLoader classLoader
) {
if (logger
.isTraceEnabled()) {
logger
.trace("Creating JDK dynamic proxy: " + this.advised
.getTargetSource());
}
Class
<?>[] proxiedInterfaces
= AopProxyUtils
.completeProxiedInterfaces(this.advised
, true);
this.findDefinedEqualsAndHashCodeMethods(proxiedInterfaces
);
return Proxy
.newProxyInstance(classLoader
, proxiedInterfaces
, this);
}
Cglib
public Object
getProxy(@Nullable ClassLoader classLoader
) {
......
return this.createProxyClassAndInstance(enhancer
, callbacks
);
}
protected Object
createProxyClassAndInstance(Enhancer enhancer
, Callback
[] callbacks
) {
enhancer
.setInterceptDuringConstruction(false);
enhancer
.setCallbacks(callbacks
);
return this.constructorArgs
!= null
&& this.constructorArgTypes
!= null
? enhancer
.create(this.constructorArgTypes
, this.constructorArgs
)
: enhancer
.create();
}