Spring 基础

1. IoC Container 基础

(1). 简单实现

一个最原始的实现(通过构造方法实例化 Bean):

class IocContainer {
    private Map<String, Object> beans = new ConcurrentHashMap<>();

    public void setBean(Class<?> clazz, String beanId, String... wiredBeanIds){
        Object[] wiredValues = new Object[wiredBeanIds.length];

        for(int i=0; i<wiredBeanIds.length; i++){
            wiredValues[i] = beans.get(wiredBeanIds[i]);
        }

        Object bean = null;
        for (Constructor<?> constructor: clazz.getConstructors()){
            try {
                bean = constructor.newInstance(wiredValues);
            } catch (InstantiationException e) {
                // do nothing.
            } catch (IllegalAccessException e) {
                // do nothing.
            } catch (InvocationTargetException e) {
                // do nothing.
            }
        }

        if (bean == null){
            throw new RuntimeException("Can not instance bean with proper constructors.");
        }

        beans.put(beanId, bean);
    }

    public Object getBean(String beanId){
        return beans.get(beanId);
    }
}
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

(2). Bean 作用域

  • singleton,默认值。一个上下文(ApplicationContext)只有一个 Bean

  • prototype,每次注入都创建一个新的对象

  • Web request,每一个 request 创建一个对象

  • Web session,每一个 session 创建一个对象

  • Web application,每一个 application 创建一个对象

  • Web websocket,每一个 web socket 创建一个对象

  • SimpleThreadScope,每一个线程创建一个对象

2. appliction.properties 常用配置

(1). 日志级别

logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG
logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE
logging.level.org.springframework.security=INFO
1
2
3

(2). 显示 SQL

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
1
2
最近更新: 8/19/2019, 10:52:28 PM