0%

最新理解

稍微总结一下 Bean 的生命周期,在 BeanFactory 这个接口的注释里面,也可以看到。

  1. 实现一堆 Aware 接口。(当实现了某个 Aware 接口后,此 Bean 就能通过 setXXX 的方法获取到容器中存在的对象)
  2. 执行 BeanPostProcessor 的 before 方法
  3. 执行 init 方法
  4. 执行 BeanPostProcessor 的 after 方法
  5. 调用 DisposableBean destroy 方法
  6. 调用 destroy 方法

下面代码里面的 @PostConstruct 和 @PreDestroy 是 javax 中的注解,和 Spring 里面的 initMethod 和 destroyMethod 还是有一定差异的。后者是 @Bean 注解里面的属性,或者在 xml 文件中定义。


Spring框架中,一旦把一个Bean纳入Spring IOC容器之中,这个Bean的生命周期就会交由容器进行管理,一般担当管理角色的是BeanFactory或者ApplicationContext。

下面以BeanFactory为例,说明一个Bean的生命周期活动。

  • Bean的建立,由BeanFactory读取Bean定义文件,并生成各个实例

  • Setter注入,执行Bean的属性依赖注入

  • BeanNameAware的setBeanName(), 如果实现该接口,则执行其setBeanName方法

  • BeanFactoryAware的setBeanFactory(),如果实现该接口,则执行其setBeanFactory方法

  • BeanPostProcessor的processBeforeInitialization(),如果有关联的processor,则在Bean初始化之前都会执行这个实例的processBeforeInitialization()方法

  • Bean定义文件中定义init-method

  • InitializingBean的afterPropertiesSet(),如果实现了该接口,则执行其afterPropertiesSet()方法

  • BeanPostProcessors的processAfterInitialization(),如果有关联的processor,则在Bean初始化之前都会执行这个实例的processAfterInitialization()方法

  • Bean定义文件中定义destroy-method,在容器关闭时,可以在 Bean 定义文件中使用 destory-method 定义的方法

  • DisposableBean的destroy(),在容器关闭时,如果 Bean 类实现了该接口,则执行它的 destroy() 方法

如果使用ApplicationContext来维护一个Bean的生命周期,则基本上与上边的流程相同,只不过在执行BeanNameAware的setBeanName()后,若有Bean类实现了org.springframework.context.ApplicationContextAware接口,则执行其setApplicationContext()方法,然后再进行BeanPostProcessors的processBeforeInitialization()

实际上,ApplicationContext除了向BeanFactory那样维护容器外,还提供了更加丰富的框架功能,如Bean的消息,事件处理机制等。

下面通过代码展示一下各个方法被调用的顺序。

1
MyBean.java
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
@Component
public class MyBean implements BeanNameAware, BeanFactoryAware, ApplicationContextAware,
InitializingBean, DisposableBean {

private static final Logger logger = LoggerFactory.getLogger(MyBean.class);

public MyBean() {
logger.info("1. MyBean Constructor");
}

@Override
public void setBeanName(String name) {
logger.info("2. BeanNameAware.setBeanName");
}

@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
logger.info("3. BeanFactoryAware.setBeanFactory");
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
logger.info("4. ApplicationContextAware.setApplicationContext");
}

@PostConstruct
public void postConstructMethod() {
logger.info("6. javax's PostConstruct");
}

@Override
public void afterPropertiesSet() throws Exception {
logger.info("7. InitializingBean.afterPropertiesSet");
}

@PreDestroy
public void preDestroyMethod() {
logger.info("9. javax's PreDestroy");
}

@Override
public void destroy() {
logger.info("10. DisposableBean.destroy");
}

}
1
MyBeanPostProcessor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

private static final Logger logger = LoggerFactory.getLogger(MyBeanPostProcessor.class);

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof MyBean) {
logger.info("5. BeanPostProcessor.postProcessBeforeInitialization");
}
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof MyBean) {
logger.info("8. BeanPostProcessor.postProcessAfterInitialization");
}
return bean;
}

}

运行结果

1
2
3
4
5
6
7
8
9
10
11
1. MyBean Constructor
2. BeanNameAware.setBeanName
3. BeanFactoryAware.setBeanFactory
4. ApplicationContextAware.setApplicationContext
5. BeanPostProcessor.postProcessBeforeInitialization
6. javax's PostConstruct
7. InitializingBean.afterPropertiesSet
8. BeanPostProcessor.postProcessAfterInitialization
Started SpringBeanLifecycleApplication in 0.632 seconds (JVM running for 1.022)
9. javax's PreDestroy
10. DisposableBean.destroy

BinaryGap

Find longest sequence of zeros in binary representation of an integer.

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

Write a function:

1
class Solution { public int solution(int N); }

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn’t contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation ‘100000’ and thus no binary gaps.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..2,147,483,647].

Copyright 2009–2019 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

Solution

数字循环除以2,直到0。每次取余,以统计1之间的0的个数。

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
class Solution {

public int solution(int N) {

int count = 0;
int maxGap = 0;
boolean first = true; // 未找到第一个1时

while (N != 0) {
if (first) {
if (N % 2 == 1) {
first = false;
}
} else {
if (N % 2 == 0) {
count ++;
} else {
// 再次遇到1时,计算之间的gap
if (count > maxGap) {
maxGap = count;
}
count = 0;
}
}
// 除以2
N >>= 1;
}

return maxGap;
}

public static void main(String[] args) {
Solution solution = new Solution();
System.out.println("Number 9 (" + Integer.toBinaryString(9) + ") gap: " + solution.solution(9));
System.out.println("Number 529 (" + Integer.toBinaryString(529) + ") gap: " + solution.solution(529));
System.out.println("Number 20 (" + Integer.toBinaryString(20) + ") gap: " + solution.solution(20));
System.out.println("Number 15 (" + Integer.toBinaryString(15) + ") gap: " + solution.solution(15));
System.out.println("Number 32 (" + Integer.toBinaryString(32) + ") gap: " + solution.solution(32));
}

}

结果如下:

1
2
3
4
5
Number 9 (1001) gap: 2
Number 529 (1000010001) gap: 4
Number 20 (10100) gap: 1
Number 15 (1111) gap: 0
Number 32 (100000) gap: 0

使用Spring Cloud Feign时遇到如下Class Not Found Error

1
2
3
4
5
6
7
8
9
10
11
12
Caused by: java.lang.NoClassDefFoundError: org/springframework/cloud/client/loadbalancer/LoadBalancedRetryFactory
at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_92]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_92]
at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_92]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:641) ~[spring-core-5.0.0.RC3.jar:5.0.0.RC3]
... 20 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_92]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_92]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_92]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_92]
... 24 common frames omitted

我使用的软件版本信息如下:

1
2
springCloudVersion = 'Finchley.M2'
springBootVersion = '2.0.0.M3'

解决办法

把openfeign的版本从原来默认的springCloudVersion改为springBootVersion,也就是2.0.0.M3

1
2
// Feign
compile("org.springframework.cloud:spring-cloud-starter-openfeign:${springBootVersion}")