点 滴


  • 首页

  • 关于

  • 分类

  • 归档

Spring 注解编程 Bean

发表于 2019-01-28 | 分类于 spring | 阅读次数:

Spring 注解编程 Bean 配置

@Configuration

@Configuration 配置类

1
2
3
4
5
6
7

import org.springframework.context.annotation.*;

@Configuration
public class MainConfig {

}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainConfigTest {

public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

// 注册 MainConfig
ctx.register(MainConfig.class);
// 刷新容器
ctx.refresh();

// 获取容器中定义的所有 bean
String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
System.out.println(beanDefinitionName);
}
ctx.close();
}
}

@Bean

xml 配置

1
2

<bean id="user" class="com.github.User"></bean>

java config

1
2
3
4
5

@Bean
public User user() {
return new User();
}

@Import

@Import 导入bean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Configuration
public class UserConfig {

@Bean
public User user() {
return new User();
}
}


@Configuration
@Import({UserConfig.class}) // 使用 import 导入 UserConfig
public class MainConfig {

}

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
User user = ctx.getBean(User.class);
System.out.println(user);
}

org.springframework.context.annotation.ImportSelector 选择导入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

public class UserImportSelector implements ImportSelector {

@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[] {"com.github.User"};
}
}

@Configuration
@Import({UserImportSelector.class})
public class MainConfig {

}

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
User user = ctx.getBean(User.class);
System.out.println(user);
}

org.springframework.context.annotation.ImportBeanDefinitionRegistrar 注册Bean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class UserRegistrar implements ImportBeanDefinitionRegistrar {

@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(User.class);
registry.registerBeanDefinition("user", beanDefinition);
}

}

@Configuration
@Import({UserRegistrar.class})
public class MainConfig {

}

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
User user = ctx.getBean(User.class);
System.out.println(user);
}

spring 注解编程中 @Enable** 组件,大量使用此种方式注册Bean。例:@EnableAspectJAutoProxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class) // 此处导入
public @interface EnableAspectJAutoProxy {

/**
* Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
* to standard Java interface-based proxies. The default is {@code false}.
*/
boolean proxyTargetClass() default false;

/**
* Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
* for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
* Off by default, i.e. no guarantees that {@code AopContext} access will work.
* @since 4.3.1
*/
boolean exposeProxy() default false;

}

@ComponentScan

@ComponentScan 指定扫描的包目录

1
2
3
4
5
6
7

package com.github;

@Component
public class User {

}
1
2
3
4
5
@Configuration
@ComponentScan({"com.github"})
public class MainConfig {

}

@Profile

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
@Configuration
public class MainConfig {


@Profile("dev")
@Bean
public User devUser() {
return new User();
}
}


public class MainConfigTest {

public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

ConfigurableEnvironment env = ctx.getEnvironment();
env.setActiveProfiles("dev"); // 设置环境为 dev

ctx.register(MainConfig.class);
ctx.refresh();

User user = ctx.getBean(User.class);
System.out.println(user);

ctx.close();
}
}

在实际开发中,经常有开发,测试,生产环境的不同配置,使用 @Profile 可以有效解决。 命令行启动设置激活的 Profile java -Dspring.profiles.actives=dev app.jar 。

initMethod destroyMethod Bean 生命周期

基于 @Bean 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

public class User {

public void initMethod() {
System.out.println("user initMethod");
}

public void destroyMethod() {
System.out.println("user destroyMethod");
}
}
@Configuration
public class MainConfig {


@Bean(initMethod="initMethod", destroyMethod="destroyMethod")
public User devUser() {
return new User();
}
}

继承 org.springframework.beans.factory.InitializingBean 和 org.springframework.beans.factory.DisposableBean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

public class User implements InitializingBean, DisposableBean {

public void afterPropertiesSet() throws Exception {
System.out.println("user initMethod");
}

public destroy() throws Exception {
System.out.println("user destroyMethod");
}
}
@Configuration
public class MainConfig {


@Bean
public User devUser() {
return new User();
}
}

使用 javax.annotation.PostConstruct 和 javax.annotation.PreDestroy。 注意这两个注解是Java规范并不是spring内置的,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class User {

@PostConstruct
public void initMethod() {
System.out.println("user initMethod");
}

@PreDestroy
public void destroyMethod() {
System.out.println("user destroyMethod");
}
}
@Configuration
public class MainConfig {


@Bean
public User devUser() {
return new User();
}
}

@Scope

scope 取值:通常使用 singleton, prototype。 web环境有 request, session。 batch 环境 step。

1
2
3
4
5
@Bean(initMethod="initMethod", destroyMethod="destroyMethod")
@Scope("prototype")
public User devUser() {
return new User();
}

默认是singleton的,这里比较一下prototype有什么不同:

  • 每次在容器中获取的 User 都会调用 devUser() 方法获取 User 实例。
  • 关闭容器不会调用 destroyMethod() 方法。

org.springframework.beans.factory.config.BeanPostProcessor 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
36
37
38
39
public interface BeanPostProcessor {

/**
* Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;

/**
* Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
* instance and the objects created by the FactoryBean (as of Spring 2.0). The
* post-processor can decide whether to apply to either the FactoryBean or created
* objects or both through corresponding {@code bean instanceof FactoryBean} checks.
* <p>This callback will also be invoked after a short-circuiting triggered by a
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
* in contrast to all other BeanPostProcessor callbacks.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.FactoryBean
*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

}

实现此接口会在spring容器初始化bean时调用

HashMap 的使用

发表于 2018-12-04 | 分类于 java | 阅读次数:

HashMap 的使用

在开发中经常使用到 HashMap,分析一下 HashMap 带参的构造方法

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
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}

/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

一个参数的构造方法,传入的参数是初始大小,最终调用两个参数的构造方法,传入初始大小和负载系数。默认的负载系数 DEFAULT_LOAD_FACTOR 是 0.75f.调用tableSizeFor(int)传入初始大小值算出threshold,具体的 tableSizeFor(int) 方法,threshold实际值会在第一次put(k,v)重新计算。

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

写一个测试 tableSizeFor 方法算出的结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void main(String[] args) {
for(int i = 0; i < 20; i++) {
System.out.println(i+":"+tableSizeFor(i));
}
}
static final int MAXIMUM_CAPACITY = 1 << 30;

static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

分析输出,这里输出的规律是,最小的2的幂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0:1
1:1
2:2
3:4
4:4
5:8
6:8
7:8
8:8
9:16
10:16
11:16
12:16
13:16
14:16
15:16
16:16
17:32
18:32
19:32

put(k,v)如果是第一次调用会直接调用resize()计算threshold分配table大小,方法在最后会判断size大小是否大于 threshold,如果插入元素大于threshold则调用resize(),然后重新计算 threshold,调整table的大小.阅读源码发现threshold计算方式是table大小乘负载系数 DEFAULT_LOAD_FACTOR.也就是说如果new HashMap(8),在第一次put(k,v)时会计算出threshold为6(负载系数0.75),在第6个参数put(k,v)时,就会重新扩容。扩容的算法使用左移<<算出结果等同*2。如果想防止二次扩容可以使用实际参数数量 / 负载系数(默认0.75) + 1.

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}

总结

如果想防止二次扩容可以使用此算法: 实际参数数量 / 负载系数(默认0.75) + 1.

maven findbugs 插件使用

发表于 2018-11-16 | 分类于 maven | 阅读次数:

Maven Findbugs 插件使用

什么是 Findbugs

Findbugs是使用静态分析查找Java代码中的错误的程序

pom 依赖

1
2
3
4
5
6
7
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>2.5.2</version>
</plugin>
</plugins>

命令

1
mvn clean compile findbugs:findbugs findbugs:gui

执行这条命令

  1. 清理 target 目录
  2. 编译 class
  3. 生成 findbugs 文件
  4. 执行 findbugs gui 程序,查看问题

基于JMS 远程分区的 spring batch

发表于 2018-10-18 | 分类于 spring | 阅读次数:

基于JMS 远程分区的 spring batch

关于 spring batch 的应用场景

通常做法

在支付系统中避免不了每天的交易结算,我们通常这样做,定时每天读取所有需要处理的交易记录,然后 for 循环处理,数据量小业务逻辑简单这样做没什么问题。如果业务复杂,就不能这么简单处理了,后期代码维护将是一个大问题。当数据量大了读取所有数据再处理也是行不通的,大量数据不可能一次全部读取到内存中,数据量大单台机处理也会很缓慢。

思考解决方案

这里可能会考虑到分批次多进程多线程处理,大致方案是读取所有需要处理数据的key,发送到mq,多台机器消费处理。

spring batch 来解决

spring batch 介绍 可以在官方文档看看,鉴于上面的场景,在 step read 前读取所有 key,然后拆分,拆分数量可以根据部署消费者数量定义,分区之后发送到mq,消费者接收到需要处理的 key 后,本地再拆分多线程处理,大致方案就是这样。

一张图来理解

jms-batch
这里 主 定义为 M, 从 定义为 S.
调度系统发送一条起批消息,哪台先抢到消费,哪台就是 M(注意:这种模式即是M也是S,除非明确指定了某一台来起批,不去监听 S 队列)。M 启动 job 执行分区逻辑,通过mq分发 key 到 S(本身 M 也监听了,所以 M 也是 S), S 收到消息执行业务逻辑(也可本地分片多线程处理),S执行完回复消息,或者 M 到数据库轮训结果。批量结束。

一个简单的demo batch-demo

迭代器 (Iterator)

发表于 2018-10-07 | 分类于 设计模式 | 阅读次数:

迭代器(Iterator)

提供按顺序访问聚合对象的元素,并不暴露聚合对象的内部表示。

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
public interface Iterator<T> {

boolean hasNext();

T next();
}


public class ConcreteIterator<Item> implements Iterator<Item> {

private Item[] items;
private int position = 0;

public ConcreteIterator(Item[] items) {
this.items = items;
}

@Override
public boolean hasNext() {
return position < items.length;
}

@Override
public Item next() {
return items[position++];
}
}

public class IteratorTest {

public static void main(String[] args) {
Integer[] items = new Integer[10];
for (int i = 0; i < items.length; i++) {
items[i] = i;
}
Iterator<Integer> iterator = new ConcreteIterator<>(items);
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
12…6

luokai

个人博客

30 日志
14 分类
16 标签
© 2019 luokai
由 Hexo 强力驱动
|
主题 — NexT.Gemini v6.0.4