Spring
Bean
- 配置一个 bean 的时候,我们可以不设置 id,也可以不设置 name,spring 默认会使用类的全限定名作为 bean 的标识符
- 如果使用 id 属性来设置 bean 的标识符,那么 id 在 spring 容器中必需唯一
- 如果同时设置 id 和 name,那么 id 设置的是标识符,name 设置的是别名
- 如果 id 和 name 的值相同,那么 spring 容器会自动检测并消除冲突:让这个 bean 只有标识符,而没有别名
- name 属性设置多个值。不设置 id,那么第一个被用作标识符,其他的被视为别名。如果设置了 id,那么 name 的所有值都是别名
- 使用
标签指定别名,别名也必须在 IoC 容器中唯一
PostConstruct
Constructor (构造方法) -> @Autowired (依赖注入) -> @PostConstruct (注释的方法)
应用:在静态方法中调用依赖注入的 Bean 中的方法
properties 配置读取
file.properties
1 | fileupload.rootpath=/Users/mac126/work |
方式一:通过 context:property-placeholder 加载配置文件
spring.xml
1
2
3
4<context:property-placeholder location="classpath:file.properties" ignore-unresolvable="true" />
<!-- 自动扫描类所在包(自动注入) - java 中引入前必须经过扫描 -->
<context:component-scan base-package="com.bjtcrj.gms.core.utils" />在 spring.xml 中引用
1
2<!-- 基本属性-->
<property name="rootpath" value="${fileupload.rootpath}" />Java 中引用
普通成员变量引用
1
2
3
4
5
public class FileGenerator {
private String rootpath;
}静态变量引用
方法一
1
2
3
4
5
6
7
8
9
public class FileGenerator {
public static String ROOTPATH;
public void setRootpath(String rootpath) {
ROOTPATH = rootpath;
}
}方法二
1
2
3
4
5
6
7
8
9
10
11
12
public class FileGenerator {
public static String ROOTPATH;
private String rootpath;
public void init() {
ROOTPATH = rootpath;
}
}
方式二:@PropertySource 注解实现配置文件加载
在 java 类文件中使用 PropertySource 注解
1
2
3
4
5
6
7
public class FileuploadProperties {
private String rootpath;
}在 java 文件中使用
1
2
private FileuploadProperties fileuploadProperties;
new 出来的对象不能自动注入对象问题
1. 新建一个工具类,比如 SpringContextUtil
1 | package com.bjtcrj.gms.common.utils; |
2. 使用
1 | private OtherClass otherClass = (OtherClass)SpringContextUtil.getBean("otherClass"); |
DataSourceUtils
根据数据源获取数据库 schema
1 | String schema = DataSourceUtils.getConnection(datasource).getCatalog(); |
注意
- 不要重复扫描包
问题
java.lang.NoClassDefFoundError: org/springframework/beans/factory/ObjectProvider
解决:从 Spring 4.3 版本以后才有这个类,可以提高版本
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 王文哲的博客!