Spring学习(四)

Bean生命周期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.xiaoguan.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class LogBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("第三步执行BeanPost处理器的before方法");
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("第五步执行BeanPost处理器的after方法");
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}

1
2
3
4
5
package com.xiaoguan.bean;

public class Student {
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.xiaoguan.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;

public class User implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware , InitializingBean,DisposableBean {
private String name;

public void setName(String name) {
System.out.println("第二步给对象的属性赋值");
this.name = name;
}

public User(){
System.out.println("第一步无参数构造方法执行了");
}
//这个方法需要自己写自己配,方法随意
public void initBean(){
System.out.println("第四步初始化bean");
}
public void destroyBean(){
System.out.println("第七步销毁Bean");
}

@Override
public void setBeanClassLoader(ClassLoader classLoader) {
System.out.println("Bean的类加载器是" + classLoader);
}

@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("bean的factory是" + beanFactory);
}

@Override
public void setBeanName(String name) {
System.out.println("bean的BeanName是:" + name);
}

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean的afterPropertiesSet执行了");
}

@Override
public void destroy() throws Exception {
System.out.println("DisposableBean实现了destoty方法执行");
}
}

1
2
3
4
5
package com.xiaoguan.bean;

public class Vip {
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean处理器将作用于整个配置文件中的所有Bean-->
<bean class="com.xiaoguan.bean.LogBeanPostProcessor"/>
<bean id="user" class="com.xiaoguan.bean.User" init-method="initBean" destroy-method="destroyBean">
<property name="name" value="张三“"/>
</bean>
<!-- <bean id="vip" class="com.xiaoguan.bean.Vip"/>-->
<!-- 在bean处理器before之前执行的需要实现Aware的相关接口-->
<!-- 在bean处理器before之后执行的需要实现InitializingBean接口-->
<!-- Bean实现了DisposableBean接口将在销毁前执行一段代码-->
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.xiaoguan.test;

import com.xiaoguan.bean.Student;
import com.xiaoguan.bean.User;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanLifecycleTest {
@Test
public void testRegisterBean(){
Student student = new Student();
System.out.println(student);
DefaultListableBeanFactory defaultListableBeanFactory = new DefaultListableBeanFactory();
defaultListableBeanFactory.registerSingleton("studentBean",student);
Object studentBean = defaultListableBeanFactory.getBean("studentBean");
System.out.println(studentBean);
}
@Test
public void testBeanLifecycle(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
User user = applicationContext.getBean("user", User.class);
System.out.println("第六部使用Bean:"+user);
ClassPathXmlApplicationContext context = (ClassPathXmlApplicationContext) applicationContext;
context.close();
}
}

Bean的循环依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.xiaoguan.bean;

public class Husband {
private String name;
private Wife wife;

public Husband() {
}

public Husband(String name, Wife wife) {
this.name = name;
this.wife = wife;
}

@Override
public String toString() {
return "Husband{" +
"name='" + name + '\'' +
", wife=" + wife.getName() +
'}';
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setWife(Wife wife) {
this.wife = wife;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.xiaoguan.bean;

public class Wife {
private String name;
private Husband husband;

public String getName() {
return name;
}

public Wife(String name, Husband husband) {
this.name = name;
this.husband = husband;
}

public Wife() {
}

@Override
public String toString() {
return "Wife{" +
"name='" + name + '\'' +
", husband=" + husband.getName() +
'}';
}

public void setName(String name) {
this.name = name;
}

public void setHusband(Husband husband) {
this.husband = husband;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.xiaoguan.test;

import com.xiaoguan.bean.Husband;
import com.xiaoguan.bean.Wife;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DependencyTest {
@Test
public void testCD(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
Husband husbandBean = applicationContext.getBean("husbandBean", Husband.class);
Wife wifeBean = applicationContext.getBean("wifeBean", Wife.class);
System.out.println(husbandBean);
System.out.println(wifeBean);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="husbandBean" class="com.xiaoguan.bean.Husband" scope="prototype">
<property name="name" value="张三"/>
<property name="wife" ref="wifeBean"/>
</bean>
<bean id="wifeBean" class="com.xiaoguan.bean.Wife" scope="singleton">
<property name="name" value="花花"/>
<property name="husband" ref="husbandBean"/>
</bean>
<!--构造方法不能构成循环依赖,只有set注入可以-->
</beans>

反射机制

1
2
3
4
5
6
7
8
9
package bean;

import com.xiaoguan.Conponent;

@Conponent("orderBean")

public class Order {
}

1
2
3
4
5
6
7
8
package bean;

import com.xiaoguan.Conponent;

@Conponent(value= "userBean")
public class User {
}

1
2
3
4
5
6
7
8
package bean;

import com.xiaoguan.Conponent;

@Conponent("vipBean")
public class Vip {
}

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.xiaoguan;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)//target元注解用来修饰Conponent注解,表名Conponent出现的位置
@Retention(RetentionPolicy.RUNTIME)//用来标注注解在什么时候可以被读取到
public @interface Conponent {
String value();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.xiaoguan;

import java.io.File;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ConponentScan {
public static void main(String[] args) {
Map<String,Object> map=new HashMap<>();
String packageName="bean";
String packagePath = packageName.replaceAll("\\.", "/");
URL url = ClassLoader.getSystemClassLoader().getResource(packagePath);
String path = url.getPath();
File file=new File(path);
File[] files = file.listFiles();
Arrays.stream(files).forEach(file1 -> {

try {
String className =packagePath+"."+ file1.getName().split("\\.")[0];
Class<?> aClass = Class.forName(className);
if (aClass.isAnnotationPresent(Conponent.class)) {
Conponent annotation = aClass.getAnnotation(Conponent.class);
String id = annotation.value();
Object o = aClass.newInstance();
map.put(id,o);

}
} catch (Exception e) {
e.printStackTrace();
}

});
System.out.println(map);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
package com.xiaoguan;

public class ReflectAnnotationTest1 {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> aClass = Class.forName("bean.User");
if (aClass.isAnnotationPresent(Conponent.class)) {
Conponent annotation = aClass.getAnnotation(Conponent.class);
System.out.println(annotation.value());
}
}
}