code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
package cn.bugstack.springframework.context.support;
import cn.bugstack.springframework.beans.factory.FactoryBean;
import cn.bugstack.springframework.beans.factory.InitializingBean;
import cn.bugstack.springframework.core.convert.ConversionService;
import cn.bugstack.springframework.core.convert.converter.Converter;
import cn.bugstack.springframework.core.convert.converter.ConverterFactory;
import cn.bugstack.springframework.core.convert.converter.ConverterRegistry;
import cn.bugstack.springframework.core.convert.converter.GenericConverter;
import cn.bugstack.springframework.core.convert.support.DefaultConversionService;
import cn.bugstack.springframework.core.convert.support.GenericConversionService;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
/**
* A factory providing convenient access to a ConversionService configured with
* converters appropriate for most environments. Set the
* setConverters "converters" property to supplement the default converters.
*
* 提供创建 ConversionService 工厂
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class ConversionServiceFactoryBean implements FactoryBean<ConversionService>, InitializingBean {
@Nullable
private Set<?> converters;
@Nullable
private GenericConversionService conversionService;
@Override
public ConversionService getObject() throws Exception {
return conversionService;
}
@Override
public Class<?> getObjectType() {
return conversionService.getClass();
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
this.conversionService = new DefaultConversionService();
registerConverters(converters, conversionService);
}
private void registerConverters(Set<?> converters, ConverterRegistry registry) {
if (converters != null) {
for (Object converter : converters) {
if (converter instanceof GenericConverter) {
registry.addConverter((GenericConverter) converter);
} else if (converter instanceof Converter<?, ?>) {
registry.addConverter((Converter<?, ?>) converter);
} else if (converter instanceof ConverterFactory<?, ?>) {
registry.addConverterFactory((ConverterFactory<?, ?>) converter);
} else {
throw new IllegalArgumentException("Each converter object must implement one of the " +
"Converter, ConverterFactory, or GenericConverter interfaces");
}
}
}
}
public void setConverters(Set<?> converters) {
this.converters = converters;
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/context/support/ConversionServiceFactoryBean.java
|
Java
|
apache-2.0
| 3,012
|
package cn.bugstack.springframework.core.convert;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Nullable;
/**
* A service interface for type conversion. This is the entry point into the convert system.
* Call {@link #convert(Object, Class)} to perform a thread-safe type conversion using this system.
*
* 类型转换抽象接口
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface ConversionService {
/** Return {@code true} if objects of {@code sourceType} can be converted to the {@code targetType}. */
boolean canConvert(@Nullable Class<?> sourceType, Class<?> targetType);
/** Convert the given {@code source} to the specified {@code targetType}. */
<T> T convert(Object source, Class<T> targetType);
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/convert/ConversionService.java
|
Java
|
apache-2.0
| 1,005
|
package cn.bugstack.springframework.core.convert.converter;
/**
* A converter converts a source object of type {@code S} to a target of type {@code T}.
*
* 类型转换处理接口
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface Converter<S, T> {
/** Convert the source object of type {@code S} to target type {@code T}. */
T convert(S source);
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/convert/converter/Converter.java
|
Java
|
apache-2.0
| 608
|
package cn.bugstack.springframework.core.convert.converter;
/**
* A factory for "ranged" converters that can convert objects from S to subtypes of R.
*
* 类型转换工厂
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface ConverterFactory<S, R>{
/**
* Get the converter to convert from S to target type T, where T is also an instance of R.
* @param <T> the target type
* @param targetType the target type to convert to
* @return a converter from S to T
*/
<T extends R> Converter<S, T> getConverter(Class<T> targetType);
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/convert/converter/ConverterFactory.java
|
Java
|
apache-2.0
| 807
|
package cn.bugstack.springframework.core.convert.converter;
/**
* For registering converters with a type conversion system.
*
* 类型转换注册接口
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface ConverterRegistry {
/**
* Add a plain converter to this registry.
* The convertible source/target type pair is derived from the Converter's parameterized types.
* @throws IllegalArgumentException if the parameterized types could not be resolved
*/
void addConverter(Converter<?, ?> converter);
/**
* Add a generic converter to this registry.
*/
void addConverter(GenericConverter converter);
/**
* Add a ranged converter factory to this registry.
* The convertible source/target type pair is derived from the ConverterFactory's parameterized types.
* @throws IllegalArgumentException if the parameterized types could not be resolved
*/
void addConverterFactory(ConverterFactory<?, ?> converterFactory);
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/convert/converter/ConverterRegistry.java
|
Java
|
apache-2.0
| 1,234
|
package cn.bugstack.springframework.core.convert.converter;
import cn.hutool.core.lang.Assert;
import java.util.Set;
/**
* Generic converter interface for converting between two or more types.
* <p>
* 通用的转换接口
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface GenericConverter {
/**
* Return the source and target types that this converter can convert between.
*/
Set<ConvertiblePair> getConvertibleTypes();
/**
* Convert the source object to the targetType described by the {@code TypeDescriptor}.
* @param source the source object to convert (may be {@code null})
* @param sourceType the type descriptor of the field we are converting from
* @param targetType the type descriptor of the field we are converting to
* @return the converted object
*/
Object convert(Object source, Class sourceType, Class targetType);
/**
* Holder for a source-to-target class pair.
*/
final class ConvertiblePair {
private final Class<?> sourceType;
private final Class<?> targetType;
public ConvertiblePair(Class<?> sourceType, Class<?> targetType) {
Assert.notNull(sourceType, "Source type must not be null");
Assert.notNull(targetType, "Target type must not be null");
this.sourceType = sourceType;
this.targetType = targetType;
}
public Class<?> getSourceType() {
return this.sourceType;
}
public Class<?> getTargetType() {
return this.targetType;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != ConvertiblePair.class) {
return false;
}
ConvertiblePair other = (ConvertiblePair) obj;
return this.sourceType.equals(other.sourceType) && this.targetType.equals(other.targetType);
}
@Override
public int hashCode() {
return this.sourceType.hashCode() * 31 + this.targetType.hashCode();
}
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/convert/converter/GenericConverter.java
|
Java
|
apache-2.0
| 2,402
|
package cn.bugstack.springframework.core.convert.support;
import cn.bugstack.springframework.core.convert.converter.ConverterRegistry;
/**
* A specialization of {@link GenericConversionService} configured by default
* with converters appropriate for most environments.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class DefaultConversionService extends GenericConversionService{
public DefaultConversionService() {
addDefaultConverters(this);
}
public static void addDefaultConverters(ConverterRegistry converterRegistry) {
// 添加各类类型转换工厂
converterRegistry.addConverterFactory(new StringToNumberConverterFactory());
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/convert/support/DefaultConversionService.java
|
Java
|
apache-2.0
| 925
|
package cn.bugstack.springframework.core.convert.support;
import cn.bugstack.springframework.core.convert.ConversionService;
import cn.bugstack.springframework.core.convert.converter.Converter;
import cn.bugstack.springframework.core.convert.converter.ConverterFactory;
import cn.bugstack.springframework.core.convert.converter.ConverterRegistry;
import cn.bugstack.springframework.core.convert.converter.GenericConverter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
/**
* Base ConversionService implementation suitable for use in most environments.
* Indirectly implements ConverterRegistry as registration API through the
* ConfigurableConversionService interface.
*
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class GenericConversionService implements ConversionService, ConverterRegistry {
private Map<GenericConverter.ConvertiblePair, GenericConverter> converters = new HashMap<>();
@Override
public boolean canConvert(Class<?> sourceType, Class<?> targetType) {
GenericConverter converter = getConverter(sourceType, targetType);
return converter != null;
}
@Override
public <T> T convert(Object source, Class<T> targetType) {
Class<?> sourceType = source.getClass();
GenericConverter converter = getConverter(sourceType, targetType);
return (T) converter.convert(source, sourceType, targetType);
}
@Override
public void addConverter(Converter<?, ?> converter) {
GenericConverter.ConvertiblePair typeInfo = getRequiredTypeInfo(converter);
ConverterAdapter converterAdapter = new ConverterAdapter(typeInfo, converter);
for (GenericConverter.ConvertiblePair convertibleType : converterAdapter.getConvertibleTypes()) {
converters.put(convertibleType, converterAdapter);
}
}
@Override
public void addConverterFactory(ConverterFactory<?, ?> converterFactory) {
GenericConverter.ConvertiblePair typeInfo = getRequiredTypeInfo(converterFactory);
ConverterFactoryAdapter converterFactoryAdapter = new ConverterFactoryAdapter(typeInfo, converterFactory);
for (GenericConverter.ConvertiblePair convertibleType : converterFactoryAdapter.getConvertibleTypes()) {
converters.put(convertibleType, converterFactoryAdapter);
}
}
@Override
public void addConverter(GenericConverter converter) {
for (GenericConverter.ConvertiblePair convertibleType : converter.getConvertibleTypes()) {
converters.put(convertibleType, converter);
}
}
private GenericConverter.ConvertiblePair getRequiredTypeInfo(Object object) {
Type[] types = object.getClass().getGenericInterfaces();
ParameterizedType parameterized = (ParameterizedType) types[0];
Type[] actualTypeArguments = parameterized.getActualTypeArguments();
Class sourceType = (Class) actualTypeArguments[0];
Class targetType = (Class) actualTypeArguments[1];
return new GenericConverter.ConvertiblePair(sourceType, targetType);
}
protected GenericConverter getConverter(Class<?> sourceType, Class<?> targetType) {
List<Class<?>> sourceCandidates = getClassHierarchy(sourceType);
List<Class<?>> targetCandidates = getClassHierarchy(targetType);
for (Class<?> sourceCandidate : sourceCandidates) {
for (Class<?> targetCandidate : targetCandidates) {
GenericConverter.ConvertiblePair convertiblePair = new GenericConverter.ConvertiblePair(sourceCandidate, targetCandidate);
GenericConverter converter = converters.get(convertiblePair);
if (converter != null) {
return converter;
}
}
}
return null;
}
private List<Class<?>> getClassHierarchy(Class<?> clazz) {
List<Class<?>> hierarchy = new ArrayList<>();
while (clazz != null) {
hierarchy.add(clazz);
clazz = clazz.getSuperclass();
}
return hierarchy;
}
private final class ConverterAdapter implements GenericConverter {
private final ConvertiblePair typeInfo;
private final Converter<Object, Object> converter;
public ConverterAdapter(ConvertiblePair typeInfo, Converter<?, ?> converter) {
this.typeInfo = typeInfo;
this.converter = (Converter<Object, Object>) converter;
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(typeInfo);
}
@Override
public Object convert(Object source, Class sourceType, Class targetType) {
return converter.convert(source);
}
}
private final class ConverterFactoryAdapter implements GenericConverter {
private final ConvertiblePair typeInfo;
private final ConverterFactory<Object, Object> converterFactory;
public ConverterFactoryAdapter(ConvertiblePair typeInfo, ConverterFactory<?, ?> converterFactory) {
this.typeInfo = typeInfo;
this.converterFactory = (ConverterFactory<Object, Object>) converterFactory;
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(typeInfo);
}
@Override
public Object convert(Object source, Class sourceType, Class targetType) {
return converterFactory.getConverter(targetType).convert(source);
}
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/convert/support/GenericConversionService.java
|
Java
|
apache-2.0
| 5,815
|
package cn.bugstack.springframework.core.convert.support;
import cn.bugstack.springframework.core.convert.converter.Converter;
import cn.bugstack.springframework.core.convert.converter.ConverterFactory;
import cn.bugstack.springframework.util.NumberUtils;
import org.jetbrains.annotations.Nullable;
/**
* Converts from a String any JDK-standard Number implementation.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class StringToNumberConverterFactory implements ConverterFactory<String, Number> {
@Override
public <T extends Number> Converter<String, T> getConverter(Class<T> targetType) {
return new StringToNumber<>(targetType);
}
private static final class StringToNumber<T extends Number> implements Converter<String, T> {
private final Class<T> targetType;
public StringToNumber(Class<T> targetType) {
this.targetType = targetType;
}
@Override
@Nullable
public T convert(String source) {
if (source.isEmpty()) {
return null;
}
return NumberUtils.parseNumber(source, this.targetType);
}
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/convert/support/StringToNumberConverterFactory.java
|
Java
|
apache-2.0
| 1,394
|
package cn.bugstack.springframework.core.io;
import cn.bugstack.springframework.util.ClassUtils;
import cn.hutool.core.lang.Assert;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class ClassPathResource implements Resource {
private final String path;
private ClassLoader classLoader;
public ClassPathResource(String path) {
this(path, (ClassLoader) null);
}
public ClassPathResource(String path, ClassLoader classLoader) {
Assert.notNull(path, "Path must not be null");
this.path = path;
this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}
@Override
public InputStream getInputStream() throws IOException {
InputStream is = classLoader.getResourceAsStream(path);
if (is == null) {
throw new FileNotFoundException(
this.path + " cannot be opened because it does not exist");
}
return is;
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/io/ClassPathResource.java
|
Java
|
apache-2.0
| 1,029
|
package cn.bugstack.springframework.core.io;
import cn.hutool.core.lang.Assert;
import java.net.MalformedURLException;
import java.net.URL;
public class DefaultResourceLoader implements ResourceLoader {
@Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()));
}
else {
try {
URL url = new URL(location);
return new UrlResource(url);
} catch (MalformedURLException e) {
return new FileSystemResource(location);
}
}
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/io/DefaultResourceLoader.java
|
Java
|
apache-2.0
| 756
|
package cn.bugstack.springframework.core.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileSystemResource implements Resource {
private final File file;
private final String path;
public FileSystemResource(File file) {
this.file = file;
this.path = file.getPath();
}
public FileSystemResource(String path) {
this.file = new File(path);
this.path = path;
}
@Override
public InputStream getInputStream() throws IOException {
return new FileInputStream(this.file);
}
public final String getPath() {
return this.path;
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/io/FileSystemResource.java
|
Java
|
apache-2.0
| 699
|
package cn.bugstack.springframework.core.io;
import java.io.IOException;
import java.io.InputStream;
public interface Resource {
InputStream getInputStream() throws IOException;
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/io/Resource.java
|
Java
|
apache-2.0
| 188
|
package cn.bugstack.springframework.core.io;
public interface ResourceLoader {
/**
* Pseudo URL prefix for loading from the class path: "classpath:"
*/
String CLASSPATH_URL_PREFIX = "classpath:";
Resource getResource(String location);
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/io/ResourceLoader.java
|
Java
|
apache-2.0
| 263
|
package cn.bugstack.springframework.core.io;
import cn.hutool.core.lang.Assert;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class UrlResource implements Resource{
private final URL url;
public UrlResource(URL url) {
Assert.notNull(url,"URL must not be null");
this.url = url;
}
@Override
public InputStream getInputStream() throws IOException {
URLConnection con = this.url.openConnection();
try {
return con.getInputStream();
}
catch (IOException ex){
if (con instanceof HttpURLConnection){
((HttpURLConnection) con).disconnect();
}
throw ex;
}
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/core/io/UrlResource.java
|
Java
|
apache-2.0
| 807
|
package cn.bugstack.springframework.jdbc;
import java.sql.SQLException;
/**
* @author zhangdd on 2022/2/9
*/
public class CannotGetJdbcConnectionException extends RuntimeException {
public CannotGetJdbcConnectionException(String message) {
super(message);
}
public CannotGetJdbcConnectionException(String message, SQLException ex) {
super(message, ex);
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/CannotGetJdbcConnectionException.java
|
Java
|
apache-2.0
| 395
|
package cn.bugstack.springframework.jdbc;
/**
* @author zhangdd on 2022/2/10
*/
public class IncorrectResultSetColumnCountException extends RuntimeException {
private final int expectedCount;
private final int actualCount;
public IncorrectResultSetColumnCountException(int expectedCount, int actualCount) {
super("Incorrect column count: expected " + expectedCount + ", actual " + actualCount);
this.expectedCount = expectedCount;
this.actualCount = actualCount;
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/IncorrectResultSetColumnCountException.java
|
Java
|
apache-2.0
| 513
|
package cn.bugstack.springframework.jdbc;
/**
* @author zhangdd on 2022/2/9
*/
public class UncategorizedSQLException extends RuntimeException{
public UncategorizedSQLException(String message) {
super(message);
}
public UncategorizedSQLException(String task,String sql, Throwable cause) {
super(sql, cause);
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/UncategorizedSQLException.java
|
Java
|
apache-2.0
| 350
|
package cn.bugstack.springframework.jdbc.core;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @author zhangdd on 2022/2/12
*/
public class ArgumentPreparedStatementSetter implements PreparedStatementSetter {
private final Object[] args;
public ArgumentPreparedStatementSetter(Object[] args) {
this.args = args;
}
@Override
public void setValues(PreparedStatement ps) throws SQLException {
if (null != args) {
for (int i = 1; i <= args.length; i++) {
ps.setObject(i, args[i - 1]);
}
}
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/ArgumentPreparedStatementSetter.java
|
Java
|
apache-2.0
| 607
|
package cn.bugstack.springframework.jdbc.core;
import cn.bugstack.springframework.jdbc.support.JdbcUtils;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 对sql的行数据 进行逐列获取放到map里
*
* @author zhangdd on 2022/2/10
*/
public class ColumnMapRowMapper implements RowMapper<Map<String, Object>> {
@Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData rsMetaData = rs.getMetaData();
int columnCount = rsMetaData.getColumnCount();
Map<String, Object> mapOfColumnValues = createColumnMap(columnCount);
for (int i = 1; i <= columnCount; i++) {
String columnName = JdbcUtils.lookupColumnName(rsMetaData, i);
mapOfColumnValues.putIfAbsent(getColumnKey(columnName), getColumnValue(rs, i));
}
return mapOfColumnValues;
}
protected Map<String, Object> createColumnMap(int columnCount) {
return new LinkedHashMap<>(columnCount);
}
protected String getColumnKey(String columnName) {
return columnName;
}
protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
return JdbcUtils.getResultSetValue(rs, index);
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/ColumnMapRowMapper.java
|
Java
|
apache-2.0
| 1,347
|
package cn.bugstack.springframework.jdbc.core;
import java.util.List;
import java.util.Map;
/**
* @author zhangdd on 2022/2/9
*/
public interface JdbcOperations {
<T> T execute(StatementCallback<T> action);
void execute(String sql);
//---------------------------------------------------------------------
// query
//---------------------------------------------------------------------
<T> T query(String sql, ResultSetExtractor<T> res);
<T> T query(String sql, Object[] args, ResultSetExtractor<T> rse);
<T> List<T> query(String sql, RowMapper<T> rowMapper);
<T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper);
<T> T query(String sql, PreparedStatementSetter pss, ResultSetExtractor<T> rse);
//---------------------------------------------------------------------
// queryForList
//---------------------------------------------------------------------
List<Map<String, Object>> queryForList(String sql);
/**
* 查询数据库表中某一个字段
*/
<T> List<T> queryForList(String sql, Class<T> elementType);
<T> List<T> queryForList(String sql, Class<T> elementType, Object... args);
List<Map<String, Object>> queryForList(String sql, Object... args);
//---------------------------------------------------------------------
// queryForObject
//---------------------------------------------------------------------
<T> T queryForObject(String sql, RowMapper<T> rowMapper);
<T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper);
/**
* 查询数据库表中 某一条记录的 某一个字段
*/
<T> T queryForObject(String sql, Class<T> requiredType);
//---------------------------------------------------------------------
// queryForMap
//---------------------------------------------------------------------
Map<String, Object> queryForMap(String sql);
Map<String, Object> queryForMap(String sql, Object... args);
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/JdbcOperations.java
|
Java
|
apache-2.0
| 2,022
|
package cn.bugstack.springframework.jdbc.core;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @author zhangdd on 2022/2/12
*/
public interface PreparedStatementCallback<T> {
T doInPreparedStatement(PreparedStatement ps) throws SQLException;
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/PreparedStatementCallback.java
|
Java
|
apache-2.0
| 276
|
package cn.bugstack.springframework.jdbc.core;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @author zhangdd on 2022/2/12
*/
public interface PreparedStatementCreator {
PreparedStatement createPreparedStatement(Connection con) throws SQLException;
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/PreparedStatementCreator.java
|
Java
|
apache-2.0
| 312
|
package cn.bugstack.springframework.jdbc.core;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @author zhangdd on 2022/2/12
*/
public interface PreparedStatementSetter {
void setValues(PreparedStatement ps) throws SQLException;
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/PreparedStatementSetter.java
|
Java
|
apache-2.0
| 262
|
package cn.bugstack.springframework.jdbc.core;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author zhangdd on 2022/2/10
*/
public interface ResultSetExtractor<T> {
T extractData(ResultSet rs) throws SQLException;
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/ResultSetExtractor.java
|
Java
|
apache-2.0
| 243
|
package cn.bugstack.springframework.jdbc.core;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* sql行转换
*
* @author zhangdd on 2022/2/10
*/
public interface RowMapper<T> {
T mapRow(ResultSet rs, int rowNum) throws SQLException;
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/RowMapper.java
|
Java
|
apache-2.0
| 261
|
package cn.bugstack.springframework.jdbc.core;
import cn.hutool.core.lang.Assert;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 将查询结果的ResultSet逐行的进行转换提取,转换成map,放到list里
*
* @author zhangdd on 2022/2/10
*/
public class RowMapperResultSetExtractor<T> implements ResultSetExtractor<List<T>> {
private final RowMapper<T> rowMapper;
private final int rowsExpected;
public RowMapperResultSetExtractor(RowMapper<T> rowMapper) {
this(rowMapper, 0);
}
public RowMapperResultSetExtractor(RowMapper<T> rowMapper, int rowsExpected) {
Assert.notNull(rowMapper, "RowMapper is required");
this.rowMapper = rowMapper;
this.rowsExpected = rowsExpected;
}
@Override
public List<T> extractData(ResultSet rs) throws SQLException {
List<T> results = this.rowsExpected > 0 ? new ArrayList<>(this.rowsExpected) : new ArrayList<>();
int rowNum = 0;
while (rs.next()) {
results.add(this.rowMapper.mapRow(rs, rowNum++));
}
return results;
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/RowMapperResultSetExtractor.java
|
Java
|
apache-2.0
| 1,163
|
package cn.bugstack.springframework.jdbc.core;
import cn.bugstack.springframework.jdbc.IncorrectResultSetColumnCountException;
import cn.bugstack.springframework.jdbc.support.JdbcUtils;
import cn.bugstack.springframework.util.NumberUtils;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/**
* @author zhangdd on 2022/2/10
*/
public class SingleColumnRowMapper<T> implements RowMapper<T> {
private Class<?> requireType;
public SingleColumnRowMapper() {
}
public SingleColumnRowMapper(Class<T> requireType) {
this.requireType = requireType;
}
@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData rsMetaData = rs.getMetaData();
int columnCount = rsMetaData.getColumnCount();
if (columnCount != 1) {
throw new IncorrectResultSetColumnCountException(1, columnCount);
}
Object result = getColumnValue(rs, 1, this.requireType);
if (result != null && this.requireType != null && !this.requireType.isInstance(result)) {
// Extracted value does not match already: try to convert it.
try {
return (T) convertValueToRequiredType(result, this.requireType);
} catch (IllegalArgumentException ex) {
}
}
return (T) result;
}
protected Object getColumnValue(ResultSet rs, int index, Class<?> requireType) throws SQLException {
if (null != requireType) {
return JdbcUtils.getResultSetValue(rs, index, requireType);
} else {
return getColumnValue(rs, index);
}
}
protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
return JdbcUtils.getResultSetValue(rs, index);
}
protected Object convertValueToRequiredType(Object value, Class<?> requiredType) {
if (String.class == requiredType) {
return value.toString();
} else if (Number.class.isAssignableFrom(requiredType)) {
if (value instanceof Number) {
// Convert original Number to target Number class.
return NumberUtils.convertNumberToTargetClass(((Number) value), (Class<Number>) requiredType);
} else {
// Convert stringified value to target Number class.
return NumberUtils.parseNumber(value.toString(), (Class<Number>) requiredType);
}
}
//这里暂时不添加spring-core里的类型转换处理
// else if (this.conversionService != null && this.conversionService.canConvert(value.getClass(), requiredType)) {
// return this.conversionService.convert(value, requiredType);
// }
else {
throw new IllegalArgumentException(
"Value [" + value + "] is of type [" + value.getClass().getName() +
"] and cannot be converted to required type [" + requiredType.getName() + "]");
}
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/SingleColumnRowMapper.java
|
Java
|
apache-2.0
| 3,040
|
package cn.bugstack.springframework.jdbc.core;
/**
* @author zhangdd on 2022/2/9
*/
public interface SqlProvider {
String getSql();
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/SqlProvider.java
|
Java
|
apache-2.0
| 142
|
package cn.bugstack.springframework.jdbc.core;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author zhangdd on 2022/2/9
*/
public interface StatementCallback<T> {
T doInStatement(Statement statement) throws SQLException;
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/core/StatementCallback.java
|
Java
|
apache-2.0
| 250
|
package cn.bugstack.springframework.jdbc.datasource;
import java.sql.Connection;
/**
* @author zhangdd on 2022/2/9
*/
public interface ConnectionHandler {
Connection getConnection();
default void releaseConnection(Connection con) {
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/datasource/ConnectionHandler.java
|
Java
|
apache-2.0
| 256
|
package cn.bugstack.springframework.jdbc.datasource;
import cn.hutool.core.lang.Assert;
import java.sql.Connection;
/**
* @author zhangdd on 2022/2/9
*/
public class ConnectionHolder {
private ConnectionHandler connectionHandler;
private Connection currentConnection;
public ConnectionHolder(ConnectionHandler connectionHandler) {
this.connectionHandler = connectionHandler;
}
public ConnectionHolder(Connection connection) {
this.connectionHandler = new SimpleConnectionHandler(connection);
}
public ConnectionHandler getConnectionHandler() {
return connectionHandler;
}
protected boolean hasConnection() {
return this.connectionHandler != null;
}
protected void setConnection(Connection connection) {
if (null != this.currentConnection) {
if (null != this.connectionHandler) {
this.connectionHandler.releaseConnection(this.currentConnection);
}
this.currentConnection = null;
}
if (null != connection) {
this.connectionHandler = new SimpleConnectionHandler(connection);
} else {
this.connectionHandler = null;
}
}
protected Connection getConnection() {
Assert.notNull(this.connectionHandler, "Active connection is required.");
if (null == this.currentConnection) {
this.currentConnection = this.connectionHandler.getConnection();
}
return this.currentConnection;
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/datasource/ConnectionHolder.java
|
Java
|
apache-2.0
| 1,535
|
package cn.bugstack.springframework.jdbc.datasource;
import cn.bugstack.springframework.jdbc.CannotGetJdbcConnectionException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* @author zhangdd on 2022/2/9
*/
public abstract class DataSourceUtils {
public static Connection getConnection(DataSource dataSource) {
try {
return doGetConnection(dataSource);
} catch (SQLException e) {
throw new CannotGetJdbcConnectionException("Failed to obtain JDBC Connection", e);
}
}
public static Connection doGetConnection(DataSource dataSource) throws SQLException {
Connection connection = fetchConnection(dataSource);
ConnectionHolder holderToUse = new ConnectionHolder(connection);
return connection;
}
private static Connection fetchConnection(DataSource dataSource) throws SQLException {
Connection conn = dataSource.getConnection();
if (null == conn) {
throw new IllegalArgumentException("DataSource return null from getConnection():" + dataSource);
}
return conn;
}
public static void releaseConnection(Connection con, DataSource dataSource) {
try {
doReleaseConnection(con, dataSource);
} catch (SQLException ex) {
// logger.debug("Could not close JDBC Connection", ex);
} catch (Throwable ex) {
// logger.debug("Unexpected exception on closing JDBC Connection", ex);
}
}
public static void doReleaseConnection(Connection con, DataSource dataSource) throws SQLException {
if (con == null) {
return;
}
doCloseConnection(con, dataSource);
}
public static void doCloseConnection(Connection con, DataSource dataSource) throws SQLException {
con.close();
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/datasource/DataSourceUtils.java
|
Java
|
apache-2.0
| 1,880
|
package cn.bugstack.springframework.jdbc.datasource;
import cn.hutool.core.lang.Assert;
import java.sql.Connection;
/**
* @author zhangdd on 2022/2/9
*/
public class SimpleConnectionHandler implements ConnectionHandler {
private final Connection connection;
public SimpleConnectionHandler(Connection connection) {
Assert.notNull(connection, "Connection must not be null");
this.connection = connection;
}
@Override
public Connection getConnection() {
return this.connection;
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/datasource/SimpleConnectionHandler.java
|
Java
|
apache-2.0
| 536
|
package cn.bugstack.springframework.jdbc.support;
import cn.bugstack.springframework.beans.factory.InitializingBean;
import javax.sql.DataSource;
/**
* @author zhangdd on 2022/2/9
*/
public abstract class JdbcAccessor implements InitializingBean {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
protected DataSource obtainDataSource() {
return getDataSource();
}
@Override
public void afterPropertiesSet() {
if (null == getDataSource()) {
throw new IllegalArgumentException("Property 'datasource' is required");
}
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/support/JdbcAccessor.java
|
Java
|
apache-2.0
| 746
|
package cn.bugstack.springframework.jdbc.support;
import cn.bugstack.springframework.jdbc.UncategorizedSQLException;
import cn.bugstack.springframework.jdbc.core.*;
import cn.bugstack.springframework.jdbc.datasource.DataSourceUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import javax.sql.DataSource;
import java.sql.*;
import java.util.List;
import java.util.Map;
/**
* @author zhangdd on 2022/2/9
*/
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
private int fetchSize = -1;
private int maxRows = -1;
private int queryTimeout = -1;
public JdbcTemplate() {
}
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
public int getFetchSize() {
return fetchSize;
}
public void setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
}
public int getMaxRows() {
return maxRows;
}
public void setMaxRows(int maxRows) {
this.maxRows = maxRows;
}
public int getQueryTimeout() {
return queryTimeout;
}
public void setQueryTimeout(int queryTimeout) {
this.queryTimeout = queryTimeout;
}
private <T> T execute(StatementCallback<T> action, boolean closeResources) {
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
stmt = con.createStatement();
applyStatementSettings(stmt);
return action.doInStatement(stmt);
} catch (SQLException e) {
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
throw translateException("ConnectionCallback", sql, e);
} finally {
if (closeResources) {
JdbcUtils.closeStatement(stmt);
}
}
}
private <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action, boolean closeResources) {
Assert.notNull(psc, "PreparedStatementCreator must not be null");
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(obtainDataSource());
PreparedStatement ps = null;
try {
ps = psc.createPreparedStatement(con);
applyStatementSettings(ps);
T result = action.doInPreparedStatement(ps);
return result;
} catch (SQLException ex) {
String sql = getSql(psc);
psc = null;
JdbcUtils.closeStatement(ps);
ps = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("PreparedStatementCallback", sql, ex);
} finally {
if (closeResources) {
JdbcUtils.closeStatement(ps);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
}
public <T> T query(
PreparedStatementCreator psc, final PreparedStatementSetter pss, final ResultSetExtractor<T> rse) {
Assert.notNull(rse, "ResultSetExtractor must not be null");
return execute(psc, new PreparedStatementCallback<T>() {
@Override
public T doInPreparedStatement(PreparedStatement ps) throws SQLException {
ResultSet rs = null;
try {
if (pss != null) {
pss.setValues(ps);
}
rs = ps.executeQuery();
return rse.extractData(rs);
} finally {
JdbcUtils.closeResultSet(rs);
}
}
}, true);
}
protected void applyStatementSettings(Statement stat) throws SQLException {
int fetchSize = getFetchSize();
if (fetchSize != -1) {
stat.setFetchSize(fetchSize);
}
int maxRows = getMaxRows();
if (maxRows != -1) {
stat.setMaxRows(maxRows);
}
}
protected UncategorizedSQLException translateException(String task, String sql, SQLException ex) {
return new UncategorizedSQLException(task, sql, ex);
}
private static String getSql(Object sqlProvider) {
if (sqlProvider instanceof SqlProvider) {
return ((SqlProvider) sqlProvider).getSql();
} else {
return null;
}
}
@Override
public <T> T execute(StatementCallback<T> action) {
return execute(action, true);
}
@Override
public void execute(String sql) {
class ExecuteStatementCallback implements StatementCallback<Object>, SqlProvider {
@Override
public Object doInStatement(Statement statement) throws SQLException {
statement.execute(sql);
return null;
}
@Override
public String getSql() {
return sql;
}
}
execute(new ExecuteStatementCallback(), true);
}
@Override
public <T> T query(String sql, ResultSetExtractor<T> res) {
Assert.notNull(sql, "SQL must not be null");
Assert.notNull(res, "ResultSetExtractor must be null");
class QueryStatementCallback implements StatementCallback<T>, SqlProvider {
@Override
public String getSql() {
return sql;
}
@Override
public T doInStatement(Statement statement) throws SQLException {
ResultSet rs = statement.executeQuery(sql);
return res.extractData(rs);
}
}
return execute(new QueryStatementCallback(), true);
}
@Override
public <T> T query(String sql, Object[] args, ResultSetExtractor<T> rse) {
return query(sql, newArgPreparedStatementSetter(args), rse);
}
@Override
public <T> List<T> query(String sql, RowMapper<T> rowMapper) {
return result(query(sql, new RowMapperResultSetExtractor<>(rowMapper)));
}
@Override
public <T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper) {
return result(query(sql, args, new RowMapperResultSetExtractor<>(rowMapper)));
}
@Override
public <T> T query(String sql, PreparedStatementSetter pss, ResultSetExtractor<T> rse) {
return query(new SimplePreparedStatementCreator(sql), pss, rse);
}
@Override
public <T> T queryForObject(String sql, RowMapper<T> rowMapper) {
List<T> results = query(sql, rowMapper);
if (CollUtil.isEmpty(results)) {
throw new RuntimeException("Incorrect result size: expected 1, actual 0");
}
if (results.size() > 1) {
throw new RuntimeException("Incorrect result size: expected 1, actual " + results.size());
}
return results.iterator().next();
}
@Override
public <T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper) {
List<T> results = query(sql, args, new RowMapperResultSetExtractor<>(rowMapper, 1));
if (CollUtil.isEmpty(results)) {
throw new RuntimeException("Incorrect result size: expected 1, actual 0");
}
if (results.size() > 1) {
throw new RuntimeException("Incorrect result size: expected 1, actual " + results.size());
}
return results.iterator().next();
}
@Override
public <T> T queryForObject(String sql, Class<T> requiredType) {
return queryForObject(sql, getSingleColumnRowMapper(requiredType));
}
@Override
public Map<String, Object> queryForMap(String sql) {
return result(queryForObject(sql, getColumnMapRowMapper()));
}
@Override
public Map<String, Object> queryForMap(String sql, Object... args) {
return result(queryForObject(sql, args, getColumnMapRowMapper()));
}
@Override
public List<Map<String, Object>> queryForList(String sql) {
return query(sql, getColumnMapRowMapper());
}
@Override
public <T> List<T> queryForList(String sql, Class<T> elementType) {
return query(sql, getSingleColumnRowMapper(elementType));
}
@Override
public <T> List<T> queryForList(String sql, Class<T> elementType, Object... args) {
return query(sql, args, getSingleColumnRowMapper(elementType));
}
@Override
public List<Map<String, Object>> queryForList(String sql, Object... args) {
return query(sql, args, getColumnMapRowMapper());
}
private static <T> T result(T result) {
Assert.state(null != result, "No result");
return result;
}
protected RowMapper<Map<String, Object>> getColumnMapRowMapper() {
return new ColumnMapRowMapper();
}
protected <T> RowMapper<T> getSingleColumnRowMapper(Class<T> requiredType) {
return new SingleColumnRowMapper<>(requiredType);
}
protected PreparedStatementSetter newArgPreparedStatementSetter(Object[] args) {
return new ArgumentPreparedStatementSetter(args);
}
private static class SimplePreparedStatementCreator implements PreparedStatementCreator, SqlProvider {
private final String sql;
public SimplePreparedStatementCreator(String sql) {
this.sql = sql;
}
@Override
public String getSql() {
return this.sql;
}
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
return con.prepareStatement(this.sql);
}
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/support/JdbcTemplate.java
|
Java
|
apache-2.0
| 9,707
|
package cn.bugstack.springframework.jdbc.support;
//import com.sun.org.slf4j.internal.Logger;
//import com.sun.org.slf4j.internal.LoggerFactory;
import cn.bugstack.springframework.util.NumberUtils;
import cn.hutool.core.util.StrUtil;
import java.math.BigDecimal;
import java.sql.*;
/**
* @author zhangdd on 2022/2/9
*/
public class JdbcUtils {
// private static final Logger logger = LoggerFactory.getLogger(JdbcUtils.class);
public static void closeStatement(Statement stmt) {
if (null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
// logger.trace("Could not close JDBC statement " + e);
}
}
}
public static void closeResultSet( ResultSet rs) {
if (rs != null) {
try {
rs.close();
}
catch (SQLException ex) {
// logger.trace("Could not close JDBC ResultSet", ex);
}
catch (Throwable ex) {
// We don't trust the JDBC driver: It might throw RuntimeException or Error.
// logger.trace("Unexpected exception on closing JDBC ResultSet", ex);
}
}
}
public static String lookupColumnName(ResultSetMetaData resultSetMetaData, int columnIndex) throws SQLException {
String name = resultSetMetaData.getColumnLabel(columnIndex);
if (StrUtil.isEmpty(name)) {
name = resultSetMetaData.getColumnName(columnIndex);
}
return name;
}
public static Object getResultSetValue(ResultSet rs, int index) throws SQLException {
Object obj = rs.getObject(index);
String className = null;
if (null != obj) {
className = obj.getClass().getName();
}
if (obj instanceof Blob) {
Blob blob = (Blob) obj;
obj = blob.getBytes(1, (int) blob.length());
} else if (obj instanceof Clob) {
Clob clob = (Clob) obj;
obj = clob.getSubString(1, (int) clob.length());
} else if ("oracle.sql.TIMESTAMP".equals(className) || "oracle.sql.TIMESTAMPTZ".equals(className)) {
obj = rs.getTimestamp(index);
} else if (null != className && className.startsWith("oracle.sql.DATE")) {
String metadataClassName = rs.getMetaData().getColumnClassName(index);
if ("java.sql.Timestamp".equals(metadataClassName) || "oracle.sql.TIMESTAMP".equals(metadataClassName)) {
obj = rs.getTimestamp(index);
} else {
obj = rs.getDate(index);
}
} else if (obj instanceof Date) {
if ("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) {
obj = rs.getDate(index);
}
}
return obj;
}
public static Object getResultSetValue(ResultSet rs, int index, Class<?> requiredType) throws SQLException {
if (null == requiredType) {
return getResultSetValue(rs, index);
}
Object value;
if (String.class == requiredType) {
return rs.getString(index);
} else if (boolean.class == requiredType || Boolean.class == requiredType) {
value = rs.getBoolean(index);
} else if (byte.class == requiredType || Byte.class == requiredType) {
value = rs.getByte(index);
} else if (short.class == requiredType || Short.class == requiredType) {
value = rs.getShort(index);
} else if (int.class == requiredType || Integer.class == requiredType) {
value = rs.getInt(index);
} else if (long.class == requiredType || Long.class == requiredType) {
value = rs.getLong(index);
} else if (float.class == requiredType || Float.class == requiredType) {
value = rs.getFloat(index);
} else if (double.class == requiredType || Double.class == requiredType ||
Number.class == requiredType) {
value = rs.getDouble(index);
} else if (BigDecimal.class == requiredType) {
return rs.getBigDecimal(index);
} else if (Date.class == requiredType) {
return rs.getDate(index);
} else if (Time.class == requiredType) {
return rs.getTime(index);
} else if (Timestamp.class == requiredType || java.util.Date.class == requiredType) {
return rs.getTimestamp(index);
} else if (byte[].class == requiredType) {
return rs.getBytes(index);
} else if (Blob.class == requiredType) {
return rs.getBlob(index);
} else if (Clob.class == requiredType) {
return rs.getClob(index);
} else if (requiredType.isEnum()) {
Object obj = rs.getObject(index);
if (obj instanceof String) {
return obj;
} else if (obj instanceof Number) {
return NumberUtils.convertNumberToTargetClass(((Number) obj), Integer.class);
} else {
return rs.getString(index);
}
} else {
return rs.getObject(index, requiredType);
}
return (rs.wasNull() ? null : value);
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/jdbc/support/JdbcUtils.java
|
Java
|
apache-2.0
| 5,249
|
package cn.bugstack.springframework.stereotype;
import java.lang.annotation.*;
/**
* Indicates that an annotated class is a "component".
* Such classes are considered as candidates for auto-detection
* when using annotation-based configuration and classpath scanning.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {
String value() default "";
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/stereotype/Component.java
|
Java
|
apache-2.0
| 416
|
package cn.bugstack.springframework.util;
import java.lang.annotation.Annotation;
import java.util.Set;
public class ClassUtils {
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
}
catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back to system class loader...
}
if (cl == null) {
// No thread context class loader -> use class loader of this class.
cl = ClassUtils.class.getClassLoader();
}
return cl;
}
/**
* Check whether the specified class is a CGLIB-generated class.
* @param clazz the class to check
*/
public static boolean isCglibProxyClass(Class<?> clazz) {
return (clazz != null && isCglibProxyClassName(clazz.getName()));
}
/**
* Check whether the specified class name is a CGLIB-generated class.
* @param className the class name to check
*/
public static boolean isCglibProxyClassName(String className) {
return (className != null && className.contains("$$"));
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/util/ClassUtils.java
|
Java
|
apache-2.0
| 1,188
|
package cn.bugstack.springframework.util;
import cn.hutool.core.lang.Assert;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class NumberUtils {
private static final BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE);
private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE);
/**
* Standard number types (all immutable):
* Byte, Short, Integer, Long, BigInteger, Float, Double, BigDecimal.
*/
public static final Set<Class<?>> STANDARD_NUMBER_TYPES;
static {
Set<Class<?>> numberTypes = new HashSet<>(8);
numberTypes.add(Byte.class);
numberTypes.add(Short.class);
numberTypes.add(Integer.class);
numberTypes.add(Long.class);
numberTypes.add(BigInteger.class);
numberTypes.add(Float.class);
numberTypes.add(Double.class);
numberTypes.add(BigDecimal.class);
STANDARD_NUMBER_TYPES = Collections.unmodifiableSet(numberTypes);
}
/**
* Convert the given number into an instance of the given target class.
* @param number the number to convert
* @param targetClass the target class to convert to
* @return the converted number
* @throws IllegalArgumentException if the target class is not supported
* (i.e. not a standard Number subclass as included in the JDK)
* @see java.lang.Byte
* @see java.lang.Short
* @see java.lang.Integer
* @see java.lang.Long
* @see java.math.BigInteger
* @see java.lang.Float
* @see java.lang.Double
* @see java.math.BigDecimal
*/
@SuppressWarnings("unchecked")
public static <T extends Number> T convertNumberToTargetClass(Number number, Class<T> targetClass)
throws IllegalArgumentException {
Assert.notNull(number, "Number must not be null");
Assert.notNull(targetClass, "Target class must not be null");
if (targetClass.isInstance(number)) {
return (T) number;
}
else if (Byte.class == targetClass) {
long value = checkedLongValue(number, targetClass);
if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return (T) Byte.valueOf(number.byteValue());
}
else if (Short.class == targetClass) {
long value = checkedLongValue(number, targetClass);
if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return (T) Short.valueOf(number.shortValue());
}
else if (Integer.class == targetClass) {
long value = checkedLongValue(number, targetClass);
if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return (T) Integer.valueOf(number.intValue());
}
else if (Long.class == targetClass) {
long value = checkedLongValue(number, targetClass);
return (T) Long.valueOf(value);
}
else if (BigInteger.class == targetClass) {
if (number instanceof BigDecimal) {
// do not lose precision - use BigDecimal's own conversion
return (T) ((BigDecimal) number).toBigInteger();
}
else {
// original value is not a Big* number - use standard long conversion
return (T) BigInteger.valueOf(number.longValue());
}
}
else if (Float.class == targetClass) {
return (T) Float.valueOf(number.floatValue());
}
else if (Double.class == targetClass) {
return (T) Double.valueOf(number.doubleValue());
}
else if (BigDecimal.class == targetClass) {
// always use BigDecimal(String) here to avoid unpredictability of BigDecimal(double)
// (see BigDecimal javadoc for details)
return (T) new BigDecimal(number.toString());
}
else {
throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
number.getClass().getName() + "] to unsupported target class [" + targetClass.getName() + "]");
}
}
/**
* Check for a {@code BigInteger}/{@code BigDecimal} long overflow
* before returning the given number as a long value.
* @param number the number to convert
* @param targetClass the target class to convert to
* @return the long value, if convertible without overflow
* @throws IllegalArgumentException if there is an overflow
* @see #raiseOverflowException
*/
private static long checkedLongValue(Number number, Class<? extends Number> targetClass) {
BigInteger bigInt = null;
if (number instanceof BigInteger) {
bigInt = (BigInteger) number;
}
else if (number instanceof BigDecimal) {
bigInt = ((BigDecimal) number).toBigInteger();
}
// Effectively analogous to JDK 8's BigInteger.longValueExact()
if (bigInt != null && (bigInt.compareTo(LONG_MIN) < 0 || bigInt.compareTo(LONG_MAX) > 0)) {
raiseOverflowException(number, targetClass);
}
return number.longValue();
}
/**
* Raise an <em>overflow</em> exception for the given number and target class.
* @param number the number we tried to convert
* @param targetClass the target class we tried to convert to
* @throws IllegalArgumentException if there is an overflow
*/
private static void raiseOverflowException(Number number, Class<?> targetClass) {
throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
number.getClass().getName() + "] to target class [" + targetClass.getName() + "]: overflow");
}
/**
* Parse the given {@code text} into a {@link Number} instance of the given
* target class, using the corresponding {@code decode} / {@code valueOf} method.
* <p>Trims all whitespace (leading, trailing, and in between characters) from
* the input {@code String} before attempting to parse the number.
* <p>Supports numbers in hex format (with leading "0x", "0X", or "#") as well.
* @param text the text to convert
* @param targetClass the target class to parse into
* @return the parsed number
* @throws IllegalArgumentException if the target class is not supported
* (i.e. not a standard Number subclass as included in the JDK)
* @see Byte#decode
* @see Short#decode
* @see Integer#decode
* @see Long#decode
* @see #decodeBigInteger(String)
* @see Float#valueOf
* @see Double#valueOf
* @see java.math.BigDecimal#BigDecimal(String)
*/
@SuppressWarnings("unchecked")
public static <T extends Number> T parseNumber(String text, Class<T> targetClass) {
Assert.notNull(text, "Text must not be null");
Assert.notNull(targetClass, "Target class must not be null");
String trimmed = trimAllWhitespace(text);
if (Byte.class == targetClass) {
return (T) (isHexNumber(trimmed) ? Byte.decode(trimmed) : Byte.valueOf(trimmed));
}
else if (Short.class == targetClass) {
return (T) (isHexNumber(trimmed) ? Short.decode(trimmed) : Short.valueOf(trimmed));
}
else if (Integer.class == targetClass) {
return (T) (isHexNumber(trimmed) ? Integer.decode(trimmed) : Integer.valueOf(trimmed));
}
else if (Long.class == targetClass) {
return (T) (isHexNumber(trimmed) ? Long.decode(trimmed) : Long.valueOf(trimmed));
}
else if (BigInteger.class == targetClass) {
return (T) (isHexNumber(trimmed) ? decodeBigInteger(trimmed) : new BigInteger(trimmed));
}
else if (Float.class == targetClass) {
return (T) Float.valueOf(trimmed);
}
else if (Double.class == targetClass) {
return (T) Double.valueOf(trimmed);
}
else if (BigDecimal.class == targetClass || Number.class == targetClass) {
return (T) new BigDecimal(trimmed);
}
else {
throw new IllegalArgumentException(
"Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]");
}
}
/**
* Parse the given {@code text} into a {@link Number} instance of the
* given target class, using the supplied {@link NumberFormat}.
* <p>Trims the input {@code String} before attempting to parse the number.
* @param text the text to convert
* @param targetClass the target class to parse into
* @param numberFormat the {@code NumberFormat} to use for parsing (if
* {@code null}, this method falls back to {@link #parseNumber(String, Class)})
* @return the parsed number
* @throws IllegalArgumentException if the target class is not supported
* (i.e. not a standard Number subclass as included in the JDK)
* @see java.text.NumberFormat#parse
* @see #convertNumberToTargetClass
* @see #parseNumber(String, Class)
*/
public static <T extends Number> T parseNumber(
String text, Class<T> targetClass, @Nullable NumberFormat numberFormat) {
if (numberFormat != null) {
Assert.notNull(text, "Text must not be null");
Assert.notNull(targetClass, "Target class must not be null");
DecimalFormat decimalFormat = null;
boolean resetBigDecimal = false;
if (numberFormat instanceof DecimalFormat) {
decimalFormat = (DecimalFormat) numberFormat;
if (BigDecimal.class == targetClass && !decimalFormat.isParseBigDecimal()) {
decimalFormat.setParseBigDecimal(true);
resetBigDecimal = true;
}
}
try {
Number number = numberFormat.parse(trimAllWhitespace(text));
return convertNumberToTargetClass(number, targetClass);
}
catch (ParseException ex) {
throw new IllegalArgumentException("Could not parse number: " + ex.getMessage());
}
finally {
if (resetBigDecimal) {
decimalFormat.setParseBigDecimal(false);
}
}
}
else {
return parseNumber(text, targetClass);
}
}
public static String trimAllWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
int len = str.length();
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
return sb.toString();
}
public static boolean hasLength(@Nullable String str) {
return (str != null && !str.isEmpty());
}
/**
* Determine whether the given {@code value} String indicates a hex number,
* i.e. needs to be passed into {@code Integer.decode} instead of
* {@code Integer.valueOf}, etc.
*/
private static boolean isHexNumber(String value) {
int index = (value.startsWith("-") ? 1 : 0);
return (value.startsWith("0x", index) || value.startsWith("0X", index) || value.startsWith("#", index));
}
/**
* Decode a {@link java.math.BigInteger} from the supplied {@link String} value.
* <p>Supports decimal, hex, and octal notation.
* @see BigInteger#BigInteger(String, int)
*/
private static BigInteger decodeBigInteger(String value) {
int radix = 10;
int index = 0;
boolean negative = false;
// Handle minus sign, if present.
if (value.startsWith("-")) {
negative = true;
index++;
}
// Handle radix specifier, if present.
if (value.startsWith("0x", index) || value.startsWith("0X", index)) {
index += 2;
radix = 16;
}
else if (value.startsWith("#", index)) {
index++;
radix = 16;
}
else if (value.startsWith("0", index) && value.length() > 1 + index) {
index++;
radix = 8;
}
BigInteger result = new BigInteger(value.substring(index), radix);
return (negative ? result.negate() : result);
}
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/util/NumberUtils.java
|
Java
|
apache-2.0
| 13,148
|
package cn.bugstack.springframework.util;
/**
* Simple strategy interface for resolving a String value.
* Used by {@link cn.bugstack.springframework.beans.factory.config.ConfigurableBeanFactory}.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface StringValueResolver {
String resolveStringValue(String strVal);
}
|
2302_77879529/spring
|
small-spring-step-18/src/main/java/cn/bugstack/springframework/util/StringValueResolver.java
|
Java
|
apache-2.0
| 569
|
package cn.bugstack.springframework.aop;
import org.aopalliance.intercept.MethodInterceptor;
/**
* Base class for AOP proxy configuration managers.
* These are not themselves AOP proxies, but subclasses of this class are
* normally factories from which AOP proxy instances are obtained directly.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class AdvisedSupport {
// ProxyConfig
private boolean proxyTargetClass = false;
// 被代理的目标对象
private TargetSource targetSource;
// 方法拦截器
private MethodInterceptor methodInterceptor;
// 方法匹配器(检查目标方法是否符合通知条件)
private MethodMatcher methodMatcher;
public boolean isProxyTargetClass() {
return proxyTargetClass;
}
public void setProxyTargetClass(boolean proxyTargetClass) {
this.proxyTargetClass = proxyTargetClass;
}
public TargetSource getTargetSource() {
return targetSource;
}
public void setTargetSource(TargetSource targetSource) {
this.targetSource = targetSource;
}
public MethodInterceptor getMethodInterceptor() {
return methodInterceptor;
}
public void setMethodInterceptor(MethodInterceptor methodInterceptor) {
this.methodInterceptor = methodInterceptor;
}
public MethodMatcher getMethodMatcher() {
return methodMatcher;
}
public void setMethodMatcher(MethodMatcher methodMatcher) {
this.methodMatcher = methodMatcher;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/AdvisedSupport.java
|
Java
|
apache-2.0
| 1,753
|
package cn.bugstack.springframework.aop;
import org.aopalliance.aop.Advice;
/**
* Base interface holding AOP <b>advice</b> (action to take at a joinpoint)
* and a filter determining the applicability of the advice (such as
* a pointcut). <i>This interface is not for use by Spring users, but to
* allow for commonality in support for different types of advice.</i>
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface Advisor {
/**
* Return the advice part of this aspect. An advice may be an
* interceptor, a before advice, a throws advice, etc.
* @return the advice that should apply if the pointcut matches
* @see org.aopalliance.intercept.MethodInterceptor
* @see BeforeAdvice
*/
Advice getAdvice();
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/Advisor.java
|
Java
|
apache-2.0
| 993
|
package cn.bugstack.springframework.aop;
import org.aopalliance.aop.Advice;
/**
* Common marker interface for before advice, such as {@link MethodBeforeAdvice}.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface BeforeAdvice extends Advice {
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/BeforeAdvice.java
|
Java
|
apache-2.0
| 491
|
package cn.bugstack.springframework.aop;
/**
* Filter that restricts matching of a pointcut or introduction to
* a given set of target classes.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface ClassFilter {
/**
* Should the pointcut apply to the given interface or target class?
* @param clazz the candidate target class
* @return whether the advice should apply to the given target class
*/
boolean matches(Class<?> clazz);
ClassFilter TRUE = TrueClassFilter.INSTANCE;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/ClassFilter.java
|
Java
|
apache-2.0
| 755
|
package cn.bugstack.springframework.aop;
import java.lang.reflect.Method;
/**
* Advice invoked before a method is invoked. Such advices cannot
* prevent the method call proceeding, unless they throw a Throwable.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface MethodBeforeAdvice extends BeforeAdvice {
/**
* Callback before a given method is invoked.
*
* @param method method being invoked
* @param args arguments to the method
* @param target target of the method invocation. May be <code>null</code>.
* @throws Throwable if this object wishes to abort the call.
* Any exception thrown will be returned to the caller if it's
* allowed by the method signature. Otherwise the exception
* will be wrapped as a runtime exception.
*/
void before(Method method, Object[] args, Object target) throws Throwable;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/MethodBeforeAdvice.java
|
Java
|
apache-2.0
| 1,177
|
package cn.bugstack.springframework.aop;
import java.lang.reflect.Method;
/**
* Part of a {@link Pointcut}: Checks whether the target method is eligible for advice.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface MethodMatcher {
/**
* Perform static checking whether the given method matches. If this
* @return whether or not this method matches statically
*/
boolean matches(Method method, Class<?> targetClass);
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/MethodMatcher.java
|
Java
|
apache-2.0
| 694
|
package cn.bugstack.springframework.aop;
/**
* Core Spring pointcut abstraction.
*
* <p>A pointcut is composed of a {@link ClassFilter} and a {@link MethodMatcher}.
* Both these basic terms and a Pointcut itself can be combined to build up combinations
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface Pointcut {
/**
* Return the ClassFilter for this pointcut.
*
* @return the ClassFilter (never <code>null</code>)
*/
ClassFilter getClassFilter();
/**
* Return the MethodMatcher for this pointcut.
*
* @return the MethodMatcher (never <code>null</code>)
*/
MethodMatcher getMethodMatcher();
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/Pointcut.java
|
Java
|
apache-2.0
| 906
|
package cn.bugstack.springframework.aop;
/**
* Superinterface for all Advisors that are driven by a pointcut.
* This covers nearly all advisors except introduction advisors,
* for which method-level matching doesn't apply.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface PointcutAdvisor extends Advisor {
/**
* Get the Pointcut that drives this advisor.
*/
Pointcut getPointcut();
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/PointcutAdvisor.java
|
Java
|
apache-2.0
| 653
|
package cn.bugstack.springframework.aop;
import cn.bugstack.springframework.util.ClassUtils;
/**
* A <code>TargetSource</code> is used to obtain the current "target" of
* an AOP invocation, which will be invoked via reflection if no around
* advice chooses to end the interceptor chain itself.
* <p>
* 被代理的目标对象
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class TargetSource {
private final Object target;
public TargetSource(Object target) {
this.target = target;
}
/**
* Return the type of targets returned by this {@link TargetSource}.
* <p>Can return <code>null</code>, although certain usages of a
* <code>TargetSource</code> might just work with a predetermined
* target class.
*
* @return the type of targets returned by this {@link TargetSource}
*/
public Class<?>[] getTargetClass() {
Class<?> clazz = this.target.getClass();
clazz = ClassUtils.isCglibProxyClass(clazz) ? clazz.getSuperclass() : clazz;
return clazz.getInterfaces();
}
/**
* Return a target instance. Invoked immediately before the
* AOP framework calls the "target" of an AOP method invocation.
*
* @return the target object, which contains the joinpoint
* @throws Exception if the target object can't be resolved
*/
public Object getTarget() {
return this.target;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/TargetSource.java
|
Java
|
apache-2.0
| 1,657
|
package cn.bugstack.springframework.aop;
/**
* @author zhangdd on 2022/2/27
*/
public class TrueClassFilter implements ClassFilter {
public static final TrueClassFilter INSTANCE = new TrueClassFilter();
private TrueClassFilter() {
}
@Override
public boolean matches(Class<?> clazz) {
return true;
}
private Object readResolve() {
return INSTANCE;
}
@Override
public String toString() {
return "ClassFilter.TRUE";
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/TrueClassFilter.java
|
Java
|
apache-2.0
| 494
|
package cn.bugstack.springframework.aop.aspectj;
import cn.bugstack.springframework.aop.ClassFilter;
import cn.bugstack.springframework.aop.MethodMatcher;
import cn.bugstack.springframework.aop.Pointcut;
import org.aspectj.weaver.tools.PointcutExpression;
import org.aspectj.weaver.tools.PointcutParser;
import org.aspectj.weaver.tools.PointcutPrimitive;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
/**
* Spring {@link cn.bugstack.springframework.aop.Pointcut} implementation
* that uses the AspectJ weaver to evaluate a pointcut expression.
* <p>
* 切点表达式
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class AspectJExpressionPointcut implements Pointcut, ClassFilter, MethodMatcher {
private static final Set<PointcutPrimitive> SUPPORTED_PRIMITIVES = new HashSet<PointcutPrimitive>();
static {
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION);
}
private final PointcutExpression pointcutExpression;
public AspectJExpressionPointcut(String expression) {
PointcutParser pointcutParser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution(SUPPORTED_PRIMITIVES, this.getClass().getClassLoader());
pointcutExpression = pointcutParser.parsePointcutExpression(expression);
}
@Override
public boolean matches(Class<?> clazz) {
return pointcutExpression.couldMatchJoinPointsInType(clazz);
}
@Override
public boolean matches(Method method, Class<?> targetClass) {
return pointcutExpression.matchesMethodExecution(method).alwaysMatches();
}
@Override
public ClassFilter getClassFilter() {
return this;
}
@Override
public MethodMatcher getMethodMatcher() {
return this;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/aspectj/AspectJExpressionPointcut.java
|
Java
|
apache-2.0
| 2,052
|
package cn.bugstack.springframework.aop.aspectj;
import cn.bugstack.springframework.aop.Pointcut;
import cn.bugstack.springframework.aop.PointcutAdvisor;
import org.aopalliance.aop.Advice;
/**
* Spring AOP Advisor that can be used for any AspectJ pointcut expression.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class AspectJExpressionPointcutAdvisor implements PointcutAdvisor {
// 切面
private AspectJExpressionPointcut pointcut;
// 具体的拦截方法
private Advice advice;
// 表达式
private String expression;
public void setExpression(String expression){
this.expression = expression;
}
@Override
public Pointcut getPointcut() {
if (null == pointcut) {
pointcut = new AspectJExpressionPointcut(expression);
}
return pointcut;
}
@Override
public Advice getAdvice() {
return advice;
}
public void setAdvice(Advice advice){
this.advice = advice;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/aspectj/AspectJExpressionPointcutAdvisor.java
|
Java
|
apache-2.0
| 1,233
|
package cn.bugstack.springframework.aop.framework;
/**
* Delegate interface for a configured AOP proxy, allowing for the creation
* of actual proxy objects.
*
* <p>Out-of-the-box implementations are available for JDK dynamic proxies
* and for CGLIB proxies, as applied by DefaultAopProxyFactory
*
* AOP 代理的抽象
*
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface AopProxy {
Object getProxy();
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/framework/AopProxy.java
|
Java
|
apache-2.0
| 666
|
package cn.bugstack.springframework.aop.framework;
import cn.bugstack.springframework.aop.AdvisedSupport;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* CGLIB2-based {@link AopProxy} implementation for the Spring AOP framework.
*
* <p><i>Requires CGLIB 2.1+ on the classpath.</i>.
* As of Spring 2.0, earlier CGLIB versions are not supported anymore.
*
* <p>Objects of this type should be obtained through proxy factories,
* configured by an AdvisedSupport object. This class is internal
* to Spring's AOP framework and need not be used directly by client code.
*/
public class Cglib2AopProxy implements AopProxy {
private final AdvisedSupport advised;
public Cglib2AopProxy(AdvisedSupport advised) {
this.advised = advised;
}
@Override
public Object getProxy() {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(advised.getTargetSource().getTarget().getClass());
enhancer.setInterfaces(advised.getTargetSource().getTargetClass());
enhancer.setCallback(new DynamicAdvisedInterceptor(advised));
return enhancer.create();
}
private static class DynamicAdvisedInterceptor implements MethodInterceptor {
private final AdvisedSupport advised;
public DynamicAdvisedInterceptor(AdvisedSupport advised) {
this.advised = advised;
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
CglibMethodInvocation methodInvocation = new CglibMethodInvocation(advised.getTargetSource().getTarget(), method, objects, methodProxy);
if (advised.getMethodMatcher().matches(method, advised.getTargetSource().getTarget().getClass())) {
return advised.getMethodInterceptor().invoke(methodInvocation);
}
return methodInvocation.proceed();
}
}
private static class CglibMethodInvocation extends ReflectiveMethodInvocation {
private final MethodProxy methodProxy;
public CglibMethodInvocation(Object target, Method method, Object[] arguments, MethodProxy methodProxy) {
super(target, method, arguments);
this.methodProxy = methodProxy;
}
@Override
public Object proceed() throws Throwable {
return this.methodProxy.invoke(this.target, this.arguments);
}
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/framework/Cglib2AopProxy.java
|
Java
|
apache-2.0
| 2,542
|
package cn.bugstack.springframework.aop.framework;
import cn.bugstack.springframework.aop.AdvisedSupport;
import org.aopalliance.intercept.MethodInterceptor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* JDK-based {@link AopProxy} implementation for the Spring AOP framework,
* based on JDK {@link java.lang.reflect.Proxy dynamic proxies}.
* <p>
* JDK 动态代理
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {
private final AdvisedSupport advised;
public JdkDynamicAopProxy(AdvisedSupport advised) {
this.advised = advised;
}
@Override
public Object getProxy() {
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), advised.getTargetSource().getTargetClass(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (advised.getMethodMatcher().matches(method, advised.getTargetSource().getTarget().getClass())) {
MethodInterceptor methodInterceptor = advised.getMethodInterceptor();
return methodInterceptor.invoke(new ReflectiveMethodInvocation(advised.getTargetSource().getTarget(), method, args));
}
return method.invoke(advised.getTargetSource().getTarget(), args);
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/framework/JdkDynamicAopProxy.java
|
Java
|
apache-2.0
| 1,639
|
package cn.bugstack.springframework.aop.framework;
import cn.bugstack.springframework.aop.AdvisedSupport;
/**
* Factory for AOP proxies for programmatic use, rather than via a bean
* factory. This class provides a simple way of obtaining and configuring
* AOP proxies in code.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class ProxyFactory {
private AdvisedSupport advisedSupport;
public ProxyFactory(AdvisedSupport advisedSupport) {
this.advisedSupport = advisedSupport;
}
public Object getProxy() {
return createAopProxy().getProxy();
}
private AopProxy createAopProxy() {
if (advisedSupport.isProxyTargetClass()) {
return new Cglib2AopProxy(advisedSupport);
}
return new JdkDynamicAopProxy(advisedSupport);
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/framework/ProxyFactory.java
|
Java
|
apache-2.0
| 1,049
|
package cn.bugstack.springframework.aop.framework;
import org.aopalliance.intercept.MethodInvocation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
/**
* <p>Invokes the target object using reflection. Subclasses can override the
* #invokeJoinpoint() method to change this behavior, so this is also
* a useful base class for more specialized MethodInvocation implementations.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class ReflectiveMethodInvocation implements MethodInvocation {
// 目标对象
protected final Object target;
// 方法
protected final Method method;
// 入参
protected final Object[] arguments;
public ReflectiveMethodInvocation(Object target, Method method, Object[] arguments) {
this.target = target;
this.method = method;
this.arguments = arguments;
}
@Override
public Method getMethod() {
return method;
}
@Override
public Object[] getArguments() {
return arguments;
}
@Override
public Object proceed() throws Throwable {
return method.invoke(target, arguments);
}
@Override
public Object getThis() {
return target;
}
@Override
public AccessibleObject getStaticPart() {
return method;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/framework/ReflectiveMethodInvocation.java
|
Java
|
apache-2.0
| 1,558
|
package cn.bugstack.springframework.aop.framework.adapter;
import cn.bugstack.springframework.aop.MethodBeforeAdvice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* Interceptor to wrap am {@link cn.bugstack.springframework.aop.MethodBeforeAdvice}.
* Used internally by the AOP framework; application developers should not need
* to use this class directly.
*/
public class MethodBeforeAdviceInterceptor implements MethodInterceptor {
private MethodBeforeAdvice advice;
public MethodBeforeAdviceInterceptor() {
}
public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
this.advice = advice;
}
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
this.advice.before(methodInvocation.getMethod(), methodInvocation.getArguments(), methodInvocation.getThis());
return methodInvocation.proceed();
}
public MethodBeforeAdvice getAdvice() {
return advice;
}
public void setAdvice(MethodBeforeAdvice advice) {
this.advice = advice;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/framework/adapter/MethodBeforeAdviceInterceptor.java
|
Java
|
apache-2.0
| 1,131
|
package cn.bugstack.springframework.aop.framework.autoproxy;
import cn.bugstack.springframework.aop.*;
import cn.bugstack.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import cn.bugstack.springframework.aop.framework.ProxyFactory;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.PropertyValues;
import cn.bugstack.springframework.beans.factory.BeanFactory;
import cn.bugstack.springframework.beans.factory.BeanFactoryAware;
import cn.bugstack.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import cn.bugstack.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* BeanPostProcessor implementation that creates AOP proxies based on all candidate
* Advisors in the current BeanFactory. This class is completely generic; it contains
* no special code to handle any particular aspects, such as pooling aspects.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class DefaultAdvisorAutoProxyCreator implements InstantiationAwareBeanPostProcessor, BeanFactoryAware {
private DefaultListableBeanFactory beanFactory;
private final Set<Object> earlyProxyReferences = Collections.synchronizedSet(new HashSet<Object>());
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = (DefaultListableBeanFactory) beanFactory;
}
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
private boolean isInfrastructureClass(Class<?> beanClass) {
return Advice.class.isAssignableFrom(beanClass) || Pointcut.class.isAssignableFrom(beanClass) || Advisor.class.isAssignableFrom(beanClass);
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (!earlyProxyReferences.contains(beanName)) {
return wrapIfNecessary(bean, beanName);
}
return bean;
}
protected Object wrapIfNecessary(Object bean, String beanName) {
if (isInfrastructureClass(bean.getClass())) return bean;
Collection<AspectJExpressionPointcutAdvisor> advisors = beanFactory.getBeansOfType(AspectJExpressionPointcutAdvisor.class).values();
for (AspectJExpressionPointcutAdvisor advisor : advisors) {
ClassFilter classFilter = advisor.getPointcut().getClassFilter();
// 过滤匹配类
if (!classFilter.matches(bean.getClass())) continue;
AdvisedSupport advisedSupport = new AdvisedSupport();
TargetSource targetSource = new TargetSource(bean);
advisedSupport.setTargetSource(targetSource);
advisedSupport.setMethodInterceptor((MethodInterceptor) advisor.getAdvice());
advisedSupport.setMethodMatcher(advisor.getPointcut().getMethodMatcher());
advisedSupport.setProxyTargetClass(true);
// 返回代理对象
return new ProxyFactory(advisedSupport).getProxy();
}
return bean;
}
@Override
public Object getEarlyBeanReference(Object bean, String beanName) {
earlyProxyReferences.add(beanName);
return wrapIfNecessary(bean, beanName);
}
@Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs, Object bean, String beanName) throws BeansException {
return pvs;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/framework/autoproxy/DefaultAdvisorAutoProxyCreator.java
|
Java
|
apache-2.0
| 4,197
|
package cn.bugstack.springframework.aop.support;
import cn.bugstack.springframework.beans.factory.BeanFactory;
import cn.bugstack.springframework.beans.factory.BeanFactoryAware;
import cn.hutool.core.lang.Assert;
import org.aopalliance.aop.Advice;
/**
* @author zhangdd on 2022/2/27
*/
public abstract class AbstractBeanFactoryPointcutAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {
private String adviceBeanName;
private BeanFactory beanFactory;
private transient volatile Advice advice;
private transient volatile Object adviceMonitor = new Object();
public void setAdviceBeanName(String adviceBeanName) {
this.adviceBeanName = adviceBeanName;
}
public String getAdviceBeanName() {
return adviceBeanName;
}
public void setAdvice(Advice advice) {
synchronized (this.adviceMonitor) {
this.advice = advice;
}
}
@Override
public Advice getAdvice() {
Advice advice = this.advice;
if (null != advice) {
return advice;
}
Assert.state(this.adviceBeanName != null, "'adviceBeanName' must be specified");
Assert.state(this.beanFactory != null, "BeanFactory must be set to resolve 'adviceBeanName'");
advice = this.beanFactory.getBean(this.adviceBeanName, Advice.class);
this.advice = advice;
return advice;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
resetAdviceMonitor();
}
private void resetAdviceMonitor() {
// if (this.beanFactory instanceof ConfigurableBeanFactory){
// this.adviceMonitor= ((ConfigurableBeanFactory) this.beanFactory).getSingleton()
// }
this.adviceMonitor = new Object();
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/support/AbstractBeanFactoryPointcutAdvisor.java
|
Java
|
apache-2.0
| 1,827
|
package cn.bugstack.springframework.aop.support;
import cn.bugstack.springframework.aop.PointcutAdvisor;
import java.io.Serializable;
/**
* @author zhangdd on 2022/2/27
*/
public abstract class AbstractPointcutAdvisor implements PointcutAdvisor, Serializable {
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/support/AbstractPointcutAdvisor.java
|
Java
|
apache-2.0
| 271
|
package cn.bugstack.springframework.aop.support;
import cn.bugstack.springframework.aop.MethodMatcher;
import java.lang.reflect.Method;
/**
* @author zhangdd on 2022/2/27
*/
public abstract class StaticMethodMatcher implements MethodMatcher {
@Override
public boolean matches(Method method, Class<?> clazz) {
throw new UnsupportedOperationException("Illegal MethodMatcher usage");
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/support/StaticMethodMatcher.java
|
Java
|
apache-2.0
| 412
|
package cn.bugstack.springframework.aop.support;
import cn.bugstack.springframework.aop.ClassFilter;
import cn.bugstack.springframework.aop.MethodMatcher;
import cn.bugstack.springframework.aop.Pointcut;
/**
* @author zhangdd on 2022/2/27
*/
public abstract class StaticMethodMatcherPointcut extends StaticMethodMatcher implements Pointcut {
private ClassFilter classFilter = ClassFilter.TRUE;
public void setClassFilter(ClassFilter classFilter) {
this.classFilter = classFilter;
}
public ClassFilter getClassFilter() {
return classFilter;
}
@Override
public MethodMatcher getMethodMatcher() {
return this;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/aop/support/StaticMethodMatcherPointcut.java
|
Java
|
apache-2.0
| 676
|
package cn.bugstack.springframework.beans;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class BeansException extends RuntimeException {
public BeansException(String msg) {
super(msg);
}
public BeansException(String msg, Throwable cause) {
super(msg, cause);
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/BeansException.java
|
Java
|
apache-2.0
| 538
|
package cn.bugstack.springframework.beans;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*
* bean 属性信息
*/
public class PropertyValue {
private final String name;
private final Object value;
public PropertyValue(String name, Object value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public Object getValue() {
return value;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/PropertyValue.java
|
Java
|
apache-2.0
| 676
|
package cn.bugstack.springframework.beans;
import java.util.ArrayList;
import java.util.List;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class PropertyValues {
private final List<PropertyValue> propertyValueList = new ArrayList<>();
public void addPropertyValue(PropertyValue pv) {
for (int i = 0; i < this.propertyValueList.size(); i++) {
PropertyValue currentPv = this.propertyValueList.get(i);
if (currentPv.getName().equals(pv.getName())) {
// 覆盖原有的属性值
this.propertyValueList.set(i, pv);
return;
}
}
this.propertyValueList.add(pv);
}
public PropertyValue[] getPropertyValues() {
return this.propertyValueList.toArray(new PropertyValue[0]);
}
public PropertyValue getPropertyValue(String propertyName) {
for (PropertyValue pv : this.propertyValueList) {
if (pv.getName().equals(propertyName)) {
return pv;
}
}
return null;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/PropertyValues.java
|
Java
|
apache-2.0
| 1,303
|
package cn.bugstack.springframework.beans.factory;
/**
* Marker superinterface indicating that a bean is eligible to be
* notified by the Spring container of a particular framework object
* through a callback-style method. Actual method signature is
* determined by individual subinterfaces, but should typically
* consist of just one void-returning method that accepts a single
* argument.
*
* 标记类接口,实现该接口可以被Spring容器感知
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface Aware {
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/Aware.java
|
Java
|
apache-2.0
| 799
|
package cn.bugstack.springframework.beans.factory;
/**
* Callback that allows a bean to be aware of the bean
* {@link ClassLoader class loader}; that is, the class loader used by the
* present bean factory to load bean classes.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface BeanClassLoaderAware extends Aware{
void setBeanClassLoader(ClassLoader classLoader);
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/BeanClassLoaderAware.java
|
Java
|
apache-2.0
| 626
|
package cn.bugstack.springframework.beans.factory;
import cn.bugstack.springframework.beans.BeansException;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface BeanFactory {
Object getBean(String name) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
/**
* Does this bean factory contain a bean definition or externally registered singleton
* instance with the given name?
* <p>If the given name is an alias, it will be translated back to the corresponding
* canonical bean name.
* <p>If this factory is hierarchical, will ask any parent factory if the bean cannot
* be found in this factory instance.
* <p>If a bean definition or singleton instance matching the given name is found,
* this method will return {@code true} whether the named bean definition is concrete
* or abstract, lazy or eager, in scope or not. Therefore, note that a {@code true}
* return value from this method does not necessarily indicate that {@link #getBean}
* will be able to obtain an instance for the same name.
* @param name the name of the bean to query
* @return whether a bean with the given name is present
*/
boolean containsBean(String name);
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/BeanFactory.java
|
Java
|
apache-2.0
| 1,650
|
package cn.bugstack.springframework.beans.factory;
import cn.bugstack.springframework.beans.BeansException;
/**
* Interface to be implemented by beans that wish to be aware of their
* owning {@link BeanFactory}.
*
* 实现此接口,既能感知到所属的 BeanFactory
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface BeanFactoryAware extends Aware {
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/BeanFactoryAware.java
|
Java
|
apache-2.0
| 679
|
package cn.bugstack.springframework.beans.factory;
/**
* Interface to be implemented by beans that want to be aware of their
* bean name in a bean factory. Note that it is not usually recommended
* that an object depend on its bean name, as this represents a potentially
* brittle dependence on external configuration, as well as a possibly
* unnecessary dependence on a Spring API.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface BeanNameAware extends Aware {
void setBeanName(String name);
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/BeanNameAware.java
|
Java
|
apache-2.0
| 753
|
package cn.bugstack.springframework.beans.factory;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.config.AutowireCapableBeanFactory;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;
import cn.bugstack.springframework.beans.factory.config.BeanPostProcessor;
import cn.bugstack.springframework.beans.factory.config.ConfigurableBeanFactory;
/**
* Configuration interface to be implemented by most listable bean factories.
* In addition to {@link ConfigurableBeanFactory}, it provides facilities to
* analyze and modify bean definitions, and to pre-instantiate singletons.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface ConfigurableListableBeanFactory extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
BeanDefinition getBeanDefinition(String beanName) throws BeansException;
void preInstantiateSingletons() throws BeansException;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/ConfigurableListableBeanFactory.java
|
Java
|
apache-2.0
| 1,206
|
package cn.bugstack.springframework.beans.factory;
/**
* Interface to be implemented by beans that want to release resources
* on destruction. A BeanFactory is supposed to invoke the destroy
* method if it disposes a cached singleton. An application context
* is supposed to dispose all of its singletons on close.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface DisposableBean {
void destroy() throws Exception;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/DisposableBean.java
|
Java
|
apache-2.0
| 672
|
package cn.bugstack.springframework.beans.factory;
/**
* Interface to be implemented by objects used within a {@link BeanFactory}
* which are themselves factories. If a bean implements this interface,
* it is used as a factory for an object to expose, not directly as a bean
* instance that will be exposed itself.
* @param <T>
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface FactoryBean<T> {
T getObject() throws Exception;
Class<?> getObjectType();
boolean isSingleton();
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/FactoryBean.java
|
Java
|
apache-2.0
| 744
|
package cn.bugstack.springframework.beans.factory;
/**
* Sub-interface implemented by bean factories that can be part
* of a hierarchy.
*/
public interface HierarchicalBeanFactory extends BeanFactory {
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/HierarchicalBeanFactory.java
|
Java
|
apache-2.0
| 209
|
package cn.bugstack.springframework.beans.factory;
/**
* Interface to be implemented by beans that need to react once all their
* properties have been set by a BeanFactory: for example, to perform custom
* initialization, or merely to check that all mandatory properties have been set.
*
* 实现此接口的 Bean 对象,会在 BeanFactory 设置属性后作出相应的处理,如:执行自定义初始化,或者仅仅检查是否设置了所有强制属性。
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface InitializingBean {
/**
* Bean 处理了属性填充后调用
*
* @throws Exception
*/
void afterPropertiesSet() throws Exception;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/InitializingBean.java
|
Java
|
apache-2.0
| 932
|
package cn.bugstack.springframework.beans.factory;
import cn.bugstack.springframework.beans.BeansException;
import java.util.Map;
/**
* Extension of the {@link BeanFactory} interface to be implemented by bean factories
* that can enumerate all their bean instances, rather than attempting bean lookup
* by name one by one as requested by clients. BeanFactory implementations that
* preload all their bean definitions (such as XML-based factories) may implement
* this interface.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface ListableBeanFactory extends BeanFactory{
/**
* 按照类型返回 Bean 实例
* @param type
* @param <T>
* @return
* @throws BeansException
*/
<T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;
/**
* Return the names of all beans defined in this registry.
*
* 返回注册表中所有的Bean名称
*/
String[] getBeanDefinitionNames();
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/ListableBeanFactory.java
|
Java
|
apache-2.0
| 1,213
|
package cn.bugstack.springframework.beans.factory;
import cn.bugstack.springframework.beans.BeansException;
/**
* Defines a factory which can return an Object instance
* (possibly shared or independent) when invoked.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface ObjectFactory<T> {
T getObject() throws BeansException;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/ObjectFactory.java
|
Java
|
apache-2.0
| 579
|
package cn.bugstack.springframework.beans.factory;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.PropertyValue;
import cn.bugstack.springframework.beans.PropertyValues;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;
import cn.bugstack.springframework.beans.factory.config.BeanFactoryPostProcessor;
import cn.bugstack.springframework.core.io.DefaultResourceLoader;
import cn.bugstack.springframework.core.io.Resource;
import cn.bugstack.springframework.util.StringValueResolver;
import java.io.IOException;
import java.util.Properties;
/**
* Allows for configuration of individual bean property values from a property resource,
* i.e. a properties file. Useful for custom config files targeted at system
* administrators that override bean properties configured in the application context.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class PropertyPlaceholderConfigurer implements BeanFactoryPostProcessor {
/**
* Default placeholder prefix: {@value}
*/
public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";
/**
* Default placeholder suffix: {@value}
*/
public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";
private String location;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
try {
// 加载属性文件
DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource(location);
// 占位符替换属性值
Properties properties = new Properties();
properties.load(resource.getInputStream());
String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
for (String beanName : beanDefinitionNames) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
PropertyValues propertyValues = beanDefinition.getPropertyValues();
for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
Object value = propertyValue.getValue();
if (!(value instanceof String)) continue;
value = resolvePlaceholder((String) value, properties);
propertyValues.addPropertyValue(new PropertyValue(propertyValue.getName(), value));
}
}
// 向容器中添加字符串解析器,供解析@Value注解使用
StringValueResolver valueResolver = new PlaceholderResolvingStringValueResolver(properties);
beanFactory.addEmbeddedValueResolver(valueResolver);
} catch (IOException e) {
throw new BeansException("Could not load properties", e);
}
}
private String resolvePlaceholder(String value, Properties properties) {
String strVal = value;
StringBuilder buffer = new StringBuilder(strVal);
int startIdx = strVal.indexOf(DEFAULT_PLACEHOLDER_PREFIX);
int stopIdx = strVal.indexOf(DEFAULT_PLACEHOLDER_SUFFIX);
if (startIdx != -1 && stopIdx != -1 && startIdx < stopIdx) {
String propKey = strVal.substring(startIdx + 2, stopIdx);
String propVal = properties.getProperty(propKey);
buffer.replace(startIdx, stopIdx + 1, propVal);
}
return buffer.toString();
}
public void setLocation(String location) {
this.location = location;
}
private class PlaceholderResolvingStringValueResolver implements StringValueResolver {
private final Properties properties;
public PlaceholderResolvingStringValueResolver(Properties properties) {
this.properties = properties;
}
@Override
public String resolveStringValue(String strVal) {
return PropertyPlaceholderConfigurer.this.resolvePlaceholder(strVal, properties);
}
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/PropertyPlaceholderConfigurer.java
|
Java
|
apache-2.0
| 4,274
|
package cn.bugstack.springframework.beans.factory.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a constructor, field, setter method or config method as to be
* autowired by Spring's dependency injection facilities.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD})
public @interface Autowired {
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/annotation/Autowired.java
|
Java
|
apache-2.0
| 781
|
package cn.bugstack.springframework.beans.factory.annotation;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.PropertyValues;
import cn.bugstack.springframework.beans.factory.BeanFactory;
import cn.bugstack.springframework.beans.factory.BeanFactoryAware;
import cn.bugstack.springframework.beans.factory.ConfigurableListableBeanFactory;
import cn.bugstack.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import cn.bugstack.springframework.core.convert.ConversionService;
import cn.bugstack.springframework.util.ClassUtils;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.TypeUtil;
import java.lang.reflect.Field;
/**
* {@link cn.bugstack.springframework.beans.factory.config.BeanPostProcessor} implementation
* that autowires annotated fields, setter methods and arbitrary config methods.
* Such members to be injected are detected through a Java 5 annotation: by default,
* Spring's {@link Autowired @Autowired} and {@link Value @Value} annotations.
* <p>
* 处理 @Value、@Autowired,注解的 BeanPostProcessor
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class AutowiredAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor, BeanFactoryAware {
private ConfigurableListableBeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
@Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs, Object bean, String beanName) throws BeansException {
// 1. 处理注解 @Value
Class<?> clazz = bean.getClass();
clazz = ClassUtils.isCglibProxyClass(clazz) ? clazz.getSuperclass() : clazz;
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
Value valueAnnotation = field.getAnnotation(Value.class);
if (null != valueAnnotation) {
Object value = valueAnnotation.value();
value = beanFactory.resolveEmbeddedValue((String) value);
// 类型转换
Class<?> sourceType = value.getClass();
Class<?> targetType = (Class<?>) TypeUtil.getType(field);
ConversionService conversionService = beanFactory.getConversionService();
if (conversionService != null) {
if (conversionService.canConvert(sourceType, targetType)) {
value = conversionService.convert(value, targetType);
}
}
BeanUtil.setFieldValue(bean, field.getName(), value);
}
}
// 2. 处理注解 @Autowired
for (Field field : declaredFields) {
Autowired autowiredAnnotation = field.getAnnotation(Autowired.class);
if (null != autowiredAnnotation) {
Class<?> fieldType = field.getType();
String dependentBeanName = null;
Qualifier qualifierAnnotation = field.getAnnotation(Qualifier.class);
Object dependentBean = null;
if (null != qualifierAnnotation) {
dependentBeanName = qualifierAnnotation.value();
dependentBean = beanFactory.getBean(dependentBeanName, fieldType);
} else {
dependentBean = beanFactory.getBean(fieldType);
}
BeanUtil.setFieldValue(bean, field.getName(), dependentBean);
}
}
return pvs;
}
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return null;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java
|
Java
|
apache-2.0
| 4,479
|
package cn.bugstack.springframework.beans.factory.annotation;
import java.lang.annotation.*;
/**
* This annotation may be used on a field or parameter as a qualifier for
* candidate beans when autowiring. It may also be used to annotate other
* custom annotations that can then in turn be used as qualifiers.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Qualifier {
String value() default "";
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/annotation/Qualifier.java
|
Java
|
apache-2.0
| 838
|
package cn.bugstack.springframework.beans.factory.annotation;
import java.lang.annotation.*;
/**
* Annotation at the field or method/constructor parameter level
* that indicates a default value expression for the affected argument.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
/**
* The actual value expression: e.g. "#{systemProperties.myProp}".
*/
String value();
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/annotation/Value.java
|
Java
|
apache-2.0
| 774
|
package cn.bugstack.springframework.beans.factory.config;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.BeanFactory;
/**
* Extension of the {@link cn.bugstack.springframework.beans.factory.BeanFactory}
* interface to be implemented by bean factories that are capable of
* autowiring, provided that they want to expose this functionality for
* existing bean instances.
*/
public interface AutowireCapableBeanFactory extends BeanFactory {
/**
* 执行 BeanPostProcessors 接口实现类的 postProcessBeforeInitialization 方法
*
* @param existingBean
* @param beanName
* @return
* @throws BeansException
*/
Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException;
/**
* 执行 BeanPostProcessors 接口实现类的 postProcessorsAfterInitialization 方法
*
* @param existingBean
* @param beanName
* @return
* @throws BeansException
*/
Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/config/AutowireCapableBeanFactory.java
|
Java
|
apache-2.0
| 1,160
|
package cn.bugstack.springframework.beans.factory.config;
import cn.bugstack.springframework.beans.PropertyValues;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class BeanDefinition {
String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;
String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;
private Class beanClass;
private PropertyValues propertyValues;
private String initMethodName;
private String destroyMethodName;
private String scope = SCOPE_SINGLETON;
private boolean singleton = true;
private boolean prototype = false;
public BeanDefinition(Class beanClass) {
this(beanClass, null);
}
public BeanDefinition(Class beanClass, PropertyValues propertyValues) {
this.beanClass = beanClass;
this.propertyValues = propertyValues != null ? propertyValues : new PropertyValues();
}
public void setScope(String scope) {
this.scope = scope;
this.singleton = SCOPE_SINGLETON.equals(scope);
this.prototype = SCOPE_PROTOTYPE.equals(scope);
}
public boolean isSingleton() {
return singleton;
}
public boolean isPrototype() {
return prototype;
}
public Class getBeanClass() {
return beanClass;
}
public void setBeanClass(Class beanClass) {
this.beanClass = beanClass;
}
public PropertyValues getPropertyValues() {
return propertyValues;
}
public void setPropertyValues(PropertyValues propertyValues) {
this.propertyValues = propertyValues;
}
public String getInitMethodName() {
return initMethodName;
}
public void setInitMethodName(String initMethodName) {
this.initMethodName = initMethodName;
}
public String getDestroyMethodName() {
return destroyMethodName;
}
public void setDestroyMethodName(String destroyMethodName) {
this.destroyMethodName = destroyMethodName;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/config/BeanDefinition.java
|
Java
|
apache-2.0
| 2,224
|
package cn.bugstack.springframework.beans.factory.config;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.ConfigurableListableBeanFactory;
/**
* Allows for custom modification of an application context's bean definitions,
* adapting the bean property values of the context's underlying bean factory.
*
* 允许自定义修改 BeanDefinition 属性信息
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface BeanFactoryPostProcessor {
/**
* 在所有的 BeanDefinition 加载完成后,实例化 Bean 对象之前,提供修改 BeanDefinition 属性的机制
*
* @param beanFactory
* @throws BeansException
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/config/BeanFactoryPostProcessor.java
|
Java
|
apache-2.0
| 1,049
|
package cn.bugstack.springframework.beans.factory.config;
import cn.bugstack.springframework.beans.BeansException;
/**
* Factory hook that allows for custom modification of new bean instances,
* e.g. checking for marker interfaces or wrapping them with proxies.
*
* 用于修改新实例化 Bean 对象的扩展点
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface BeanPostProcessor {
/**
* 在 Bean 对象执行初始化方法之前,执行此方法
*
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
/**
* 在 Bean 对象执行初始化方法之后,执行此方法
*
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/config/BeanPostProcessor.java
|
Java
|
apache-2.0
| 1,187
|
package cn.bugstack.springframework.beans.factory.config;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*
* Bean 的引用
*/
public class BeanReference {
private final String beanName;
public BeanReference(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/config/BeanReference.java
|
Java
|
apache-2.0
| 577
|
package cn.bugstack.springframework.beans.factory.config;
import cn.bugstack.springframework.beans.factory.HierarchicalBeanFactory;
import cn.bugstack.springframework.core.convert.ConversionService;
import cn.bugstack.springframework.util.StringValueResolver;
import org.jetbrains.annotations.Nullable;
/**
* Configuration interface to be implemented by most bean factories. Provides
* facilities to configure a bean factory, in addition to the bean factory
* client methods in the {@link cn.bugstack.springframework.beans.factory.BeanFactory}
* interface.
*/
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
String SCOPE_SINGLETON = "singleton";
String SCOPE_PROTOTYPE = "prototype";
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);
/**
* 销毁单例对象
*/
void destroySingletons();
/**
* Add a String resolver for embedded values such as annotation attributes.
* @param valueResolver the String resolver to apply to embedded values
* @since 3.0
*/
void addEmbeddedValueResolver(StringValueResolver valueResolver);
/**
* Resolve the given embedded value, e.g. an annotation attribute.
* @param value the value to resolve
* @return the resolved value (may be the original value as-is)
* @since 3.0
*/
String resolveEmbeddedValue(String value);
/**
* Specify a Spring 3.0 ConversionService to use for converting
* property values, as an alternative to JavaBeans PropertyEditors.
* @since 3.0
*/
void setConversionService(ConversionService conversionService);
/**
* Return the associated ConversionService, if any.
* @since 3.0
*/
@Nullable
ConversionService getConversionService();
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/config/ConfigurableBeanFactory.java
|
Java
|
apache-2.0
| 1,813
|
package cn.bugstack.springframework.beans.factory.config;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.PropertyValues;
/**
* Subinterface of {@link BeanPostProcessor} that adds a before-instantiation callback,
* and a callback after instantiation but before explicit properties are set or
* autowiring occurs.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
/**
* Apply this BeanPostProcessor <i>before the target bean gets instantiated</i>.
* The returned bean object may be a proxy to use instead of the target bean,
* effectively suppressing default instantiation of the target bean.
* <p>
* 在 Bean 对象执行初始化方法之前,执行此方法
*
* @param beanClass
* @param beanName
* @return
* @throws BeansException
*/
Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;
/**
* Perform operations after the bean has been instantiated, via a constructor or factory method,
* but before Spring property population (from explicit properties or autowiring) occurs.
* <p>This is the ideal callback for performing field injection on the given bean instance.
* See Spring's own {@link cn.bugstack.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor}
* for a typical example.
* <p>
* 在 Bean 对象执行初始化方法之后,执行此方法
*
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;
/**
* Post-process the given property values before the factory applies them
* to the given bean. Allows for checking whether all dependencies have been
* satisfied, for example based on a "Required" annotation on bean property setters.
* <p>
* 在 Bean 对象实例化完成后,设置属性操作之前执行此方法
*
* @param pvs
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
PropertyValues postProcessPropertyValues(PropertyValues pvs, Object bean, String beanName) throws BeansException;
/**
* 在 Spring 中由 SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference 提供
* @param bean
* @param beanName
* @return
*/
default Object getEarlyBeanReference(Object bean, String beanName) {
return bean;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/config/InstantiationAwareBeanPostProcessor.java
|
Java
|
apache-2.0
| 2,856
|
package cn.bugstack.springframework.beans.factory.config;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
* <p>
* 单例注册表
*/
public interface SingletonBeanRegistry {
Object getSingleton(String beanName);
void registerSingleton(String beanName, Object singletonObject);
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/config/SingletonBeanRegistry.java
|
Java
|
apache-2.0
| 568
|
package cn.bugstack.springframework.beans.factory.support;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.PropertyValue;
import cn.bugstack.springframework.beans.PropertyValues;
import cn.bugstack.springframework.beans.factory.*;
import cn.bugstack.springframework.beans.factory.config.*;
import cn.bugstack.springframework.context.ApplicationContextAware;
import cn.bugstack.springframework.core.convert.ConversionService;
import cn.bugstack.springframework.util.ClassUtils;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.BasicType;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.TypeUtil;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Abstract bean factory superclass that implements default bean creation,
* with the full capabilities specified by the class.
* Implements the {@link cn.bugstack.springframework.beans.factory.config.AutowireCapableBeanFactory}
* interface in addition to AbstractBeanFactory's {@link #createBean} method.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();
@Override
protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
// 判断是否返回代理 Bean 对象
Object bean = resolveBeforeInstantiation(beanName, beanDefinition);
if (null != bean) {
return bean;
}
return doCreateBean(beanName, beanDefinition, args);
}
protected Object doCreateBean(String beanName, BeanDefinition beanDefinition, Object[] args) {
Object bean = null;
try {
// 实例化 Bean
bean = createBeanInstance(beanDefinition, beanName, args);
// 处理循环依赖,将实例化后的Bean对象提前放入缓存中暴露出来
if (beanDefinition.isSingleton()) {
Object finalBean = bean;
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, beanDefinition, finalBean));
}
// 实例化后判断
boolean continueWithPropertyPopulation = applyBeanPostProcessorsAfterInstantiation(beanName, bean);
if (!continueWithPropertyPopulation) {
return bean;
}
// 在设置 Bean 属性之前,允许 BeanPostProcessor 修改属性值
applyBeanPostProcessorsBeforeApplyingPropertyValues(beanName, bean, beanDefinition);
// 给 Bean 填充属性
applyPropertyValues(beanName, bean, beanDefinition);
// 执行 Bean 的初始化方法和 BeanPostProcessor 的前置和后置处理方法
bean = initializeBean(beanName, bean, beanDefinition);
} catch (Exception e) {
throw new BeansException("Instantiation of bean failed", e);
}
// 注册实现了 DisposableBean 接口的 Bean 对象
registerDisposableBeanIfNecessary(beanName, bean, beanDefinition);
// 判断 SCOPE_SINGLETON、SCOPE_PROTOTYPE
Object exposedObject = bean;
if (beanDefinition.isSingleton()) {
// 获取代理对象
exposedObject = getSingleton(beanName);
registerSingleton(beanName, exposedObject);
}
return exposedObject;
}
protected Object getEarlyBeanReference(String beanName, BeanDefinition beanDefinition, Object bean) {
Object exposedObject = bean;
for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
exposedObject = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).getEarlyBeanReference(exposedObject, beanName);
if (null == exposedObject) return exposedObject;
}
}
return exposedObject;
}
/**
* Bean 实例化后对于返回 false 的对象,不在执行后续设置 Bean 对象属性的操作
*
* @param beanName
* @param bean
* @return
*/
private boolean applyBeanPostProcessorsAfterInstantiation(String beanName, Object bean) {
boolean continueWithPropertyPopulation = true;
for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor instantiationAwareBeanPostProcessor = (InstantiationAwareBeanPostProcessor) beanPostProcessor;
if (!instantiationAwareBeanPostProcessor.postProcessAfterInstantiation(bean, beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
return continueWithPropertyPopulation;
}
/**
* 在设置 Bean 属性之前,允许 BeanPostProcessor 修改属性值
*
* @param beanName
* @param bean
* @param beanDefinition
*/
protected void applyBeanPostProcessorsBeforeApplyingPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
PropertyValues pvs = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessPropertyValues(beanDefinition.getPropertyValues(), bean, beanName);
if (null != pvs) {
for (PropertyValue propertyValue : pvs.getPropertyValues()) {
beanDefinition.getPropertyValues().addPropertyValue(propertyValue);
}
}
}
}
}
protected Object resolveBeforeInstantiation(String beanName, BeanDefinition beanDefinition) {
Object bean = applyBeanPostProcessorsBeforeInstantiation(beanDefinition.getBeanClass(), beanName);
if (null != bean) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
return bean;
}
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
Object result = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessBeforeInstantiation(beanClass, beanName);
if (null != result) return result;
}
}
return null;
}
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) {
// 非 Singleton 类型的 Bean 不执行销毁方法
if (!beanDefinition.isSingleton()) return;
if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) {
registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition));
}
}
protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) {
Constructor constructorToUse = null;
Class<?> beanClass = beanDefinition.getBeanClass();
Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
for (Constructor ctor : declaredConstructors) {
if (null != args && ctor.getParameterTypes().length == args.length) {
constructorToUse = ctor;
break;
}
}
return getInstantiationStrategy().instantiate(beanDefinition, beanName, constructorToUse, args);
}
/**
* Bean 属性填充
*/
protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
try {
PropertyValues propertyValues = beanDefinition.getPropertyValues();
for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
String name = propertyValue.getName();
Object value = propertyValue.getValue();
if (value instanceof BeanReference) {
// A 依赖 B,获取 B 的实例化
BeanReference beanReference = (BeanReference) value;
value = getBean(beanReference.getBeanName());
}
// 类型转换
else {
Class<?> sourceType = value.getClass();
Class<?> targetType = (Class<?>) TypeUtil.getFieldType(bean.getClass(), name);
ConversionService conversionService = getConversionService();
if (conversionService != null) {
if (conversionService.canConvert(sourceType, targetType)) {
value = conversionService.convert(value, targetType);
}
}
}
// 反射设置属性填充
BeanUtil.setFieldValue(bean, name, value);
}
} catch (Exception e) {
throw new BeansException("Error setting property values:" + beanName + " message:" + e);
}
}
public InstantiationStrategy getInstantiationStrategy() {
return instantiationStrategy;
}
public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
this.instantiationStrategy = instantiationStrategy;
}
private Object initializeBean(String beanName, Object bean, BeanDefinition beanDefinition) {
// invokeAwareMethods
if (bean instanceof Aware) {
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(this);
}
if (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
}
// 1. 执行 BeanPostProcessor Before 处理
Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);
// 执行 Bean 对象的初始化方法
try {
invokeInitMethods(beanName, wrappedBean, beanDefinition);
} catch (Exception e) {
throw new BeansException("Invocation of init method of bean[" + beanName + "] failed", e);
}
// 2. 执行 BeanPostProcessor After 处理
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
return wrappedBean;
}
private void invokeInitMethods(String beanName, Object bean, BeanDefinition beanDefinition) throws Exception {
// 1. 实现接口 InitializingBean
if (bean instanceof InitializingBean) {
((InitializingBean) bean).afterPropertiesSet();
}
// 2. 注解配置 init-method {判断是为了避免二次执行销毁}
String initMethodName = beanDefinition.getInitMethodName();
if (StrUtil.isNotEmpty(initMethodName)) {
Method initMethod = beanDefinition.getBeanClass().getMethod(initMethodName);
if (null == initMethod) {
throw new BeansException("Could not find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'");
}
initMethod.invoke(bean);
}
}
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (null == current) return result;
result = current;
}
return result;
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (null == current) return result;
result = current;
}
return result;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
|
Java
|
apache-2.0
| 12,924
|
package cn.bugstack.springframework.beans.factory.support;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.core.io.DefaultResourceLoader;
import cn.bugstack.springframework.core.io.ResourceLoader;
/**
* Abstract base class for bean definition readers which implement
* the {@link BeanDefinitionReader} interface.
* <p>
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public abstract class AbstractBeanDefinitionReader implements BeanDefinitionReader {
private final BeanDefinitionRegistry registry;
private ResourceLoader resourceLoader;
protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, new DefaultResourceLoader());
}
public AbstractBeanDefinitionReader(BeanDefinitionRegistry registry, ResourceLoader resourceLoader) {
this.registry = registry;
this.resourceLoader = resourceLoader;
}
@Override
public BeanDefinitionRegistry getRegistry() {
return registry;
}
@Override
public ResourceLoader getResourceLoader() {
return resourceLoader;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/AbstractBeanDefinitionReader.java
|
Java
|
apache-2.0
| 1,353
|
package cn.bugstack.springframework.beans.factory.support;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.BeanFactory;
import cn.bugstack.springframework.beans.factory.FactoryBean;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;
import cn.bugstack.springframework.beans.factory.config.BeanPostProcessor;
import cn.bugstack.springframework.beans.factory.config.ConfigurableBeanFactory;
import cn.bugstack.springframework.core.convert.ConversionService;
import cn.bugstack.springframework.util.ClassUtils;
import cn.bugstack.springframework.util.StringValueResolver;
import java.util.ArrayList;
import java.util.List;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
* <p>
* BeanDefinition注册表接口
*/
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
/**
* ClassLoader to resolve bean class names with, if necessary
*/
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
/**
* BeanPostProcessors to apply in createBean
*/
private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();
/**
* String resolvers to apply e.g. to annotation attribute values
*/
private final List<StringValueResolver> embeddedValueResolvers = new ArrayList<>();
private ConversionService conversionService;
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null);
}
@Override
public Object getBean(String name, Object... args) throws BeansException {
return doGetBean(name, args);
}
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return (T) getBean(name);
}
@Override
public boolean containsBean(String name) {
return containsBeanDefinition(name);
}
protected abstract boolean containsBeanDefinition(String beanName);
protected <T> T doGetBean(final String name, final Object[] args) {
Object sharedInstance = getSingleton(name);
if (sharedInstance != null) {
// 如果是 FactoryBean,则需要调用 FactoryBean#getObject
return (T) getObjectForBeanInstance(sharedInstance, name);
}
BeanDefinition beanDefinition = getBeanDefinition(name);
Object bean = createBean(name, beanDefinition, args);
return (T) getObjectForBeanInstance(bean, name);
}
private Object getObjectForBeanInstance(Object beanInstance, String beanName) {
if (!(beanInstance instanceof FactoryBean)) {
return beanInstance;
}
Object object = getCachedObjectForFactoryBean(beanName);
if (object == null) {
FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
object = getObjectFromFactoryBean(factoryBean, beanName);
}
return object;
}
protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;
protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;
@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
this.beanPostProcessors.remove(beanPostProcessor);
this.beanPostProcessors.add(beanPostProcessor);
}
@Override
public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
this.embeddedValueResolvers.add(valueResolver);
}
@Override
public String resolveEmbeddedValue(String value) {
String result = value;
for (StringValueResolver resolver : this.embeddedValueResolvers) {
result = resolver.resolveStringValue(result);
}
return result;
}
@Override
public void setConversionService(ConversionService conversionService) {
this.conversionService = conversionService;
}
@Override
public ConversionService getConversionService() {
return conversionService;
}
/**
* Return the list of BeanPostProcessors that will get applied
* to beans created with this factory.
*/
public List<BeanPostProcessor> getBeanPostProcessors() {
return this.beanPostProcessors;
}
public ClassLoader getBeanClassLoader() {
return this.beanClassLoader;
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/AbstractBeanFactory.java
|
Java
|
apache-2.0
| 4,693
|
package cn.bugstack.springframework.beans.factory.support;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.core.io.Resource;
import cn.bugstack.springframework.core.io.ResourceLoader;
/**
* Simple interface for bean definition readers.
*
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface BeanDefinitionReader {
BeanDefinitionRegistry getRegistry();
ResourceLoader getResourceLoader();
void loadBeanDefinitions(Resource resource) throws BeansException;
void loadBeanDefinitions(Resource... resources) throws BeansException;
void loadBeanDefinitions(String location) throws BeansException;
void loadBeanDefinitions(String... locations) throws BeansException;
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/BeanDefinitionReader.java
|
Java
|
apache-2.0
| 979
|
package cn.bugstack.springframework.beans.factory.support;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public interface BeanDefinitionRegistry {
/**
* 向注册表中注册 BeanDefinition
*
* @param beanName
* @param beanDefinition
*/
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition);
/**
* 使用Bean名称查询BeanDefinition
*
* @param beanName
* @return
* @throws BeansException
*/
BeanDefinition getBeanDefinition(String beanName) throws BeansException;
/**
* 判断是否包含指定名称的BeanDefinition
* @param beanName
* @return
*/
boolean containsBeanDefinition(String beanName);
/**
* Return the names of all beans defined in this registry.
*
* 返回注册表中所有的Bean名称
*/
String[] getBeanDefinitionNames();
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/BeanDefinitionRegistry.java
|
Java
|
apache-2.0
| 1,261
|
package cn.bugstack.springframework.beans.factory.support;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;
import java.lang.reflect.Constructor;
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {
@Override
public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(beanDefinition.getBeanClass());
enhancer.setCallback(new NoOp() {
@Override
public int hashCode() {
return super.hashCode();
}
});
if (null == ctor) return enhancer.create();
return enhancer.create(ctor.getParameterTypes(), args);
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java
|
Java
|
apache-2.0
| 932
|
package cn.bugstack.springframework.beans.factory.support;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.ConfigurableListableBeanFactory;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;
import cn.bugstack.springframework.beans.factory.config.ConfigurableBeanFactory;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry, ConfigurableListableBeanFactory {
private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
beanDefinitionMap.put(beanName, beanDefinition);
}
@Override
public boolean containsBeanDefinition(String beanName) {
return beanDefinitionMap.containsKey(beanName);
}
@Override
public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
Map<String, T> result = new HashMap<>();
beanDefinitionMap.forEach((beanName, beanDefinition) -> {
Class beanClass = beanDefinition.getBeanClass();
if (type.isAssignableFrom(beanClass)) {
result.put(beanName, (T) getBean(beanName));
}
});
return result;
}
@Override
public String[] getBeanDefinitionNames() {
return beanDefinitionMap.keySet().toArray(new String[0]);
}
@Override
public BeanDefinition getBeanDefinition(String beanName) throws BeansException {
BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
if (beanDefinition == null) throw new BeansException("No bean named '" + beanName + "' is defined");
return beanDefinition;
}
@Override
public void preInstantiateSingletons() throws BeansException {
beanDefinitionMap.keySet().forEach(this::getBean);
}
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
List<String> beanNames = new ArrayList<>();
for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
Class beanClass = entry.getValue().getBeanClass();
if (requiredType.isAssignableFrom(beanClass)) {
beanNames.add(entry.getKey());
}
}
if (1 == beanNames.size()) {
return getBean(beanNames.get(0), requiredType);
}
throw new BeansException(requiredType + "expected single bean but found " + beanNames.size() + ": " + beanNames);
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/DefaultListableBeanFactory.java
|
Java
|
apache-2.0
| 2,946
|
package cn.bugstack.springframework.beans.factory.support;
import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.DisposableBean;
import cn.bugstack.springframework.beans.factory.ObjectFactory;
import cn.bugstack.springframework.beans.factory.config.SingletonBeanRegistry;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*
* 来自于对开源项目的学习;
* 作者:DerekYRC https://github.com/DerekYRC/mini-spring
*/
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {
/**
* Internal marker for a null singleton object:
* used as marker value for concurrent Maps (which don't support null values).
*/
protected static final Object NULL_OBJECT = new Object();
// 一级缓存,普通对象
/**
* Cache of singleton objects: bean name --> bean instance
*/
private Map<String, Object> singletonObjects = new ConcurrentHashMap<>();
// 二级缓存,提前暴漏对象,没有完全实例化的对象
/**
* Cache of early singleton objects: bean name --> bean instance
*/
protected final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>();
// 三级缓存,存放代理对象
/**
* Cache of singleton factories: bean name --> ObjectFactory
*/
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>();
private final Map<String, DisposableBean> disposableBeans = new LinkedHashMap<>();
@Override
public Object getSingleton(String beanName) {
Object singletonObject = singletonObjects.get(beanName);
if (null == singletonObject) {
singletonObject = earlySingletonObjects.get(beanName);
// 判断二级缓存中是否有对象,这个对象就是代理对象,因为只有代理对象才会放到三级缓存中
if (null == singletonObject) {
ObjectFactory<?> singletonFactory = singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
// 把三级缓存中的代理对象中的真实对象获取出来,放入二级缓存中
earlySingletonObjects.put(beanName, singletonObject);
singletonFactories.remove(beanName);
}
}
}
return singletonObject;
}
public void registerSingleton(String beanName, Object singletonObject) {
singletonObjects.put(beanName, singletonObject);
earlySingletonObjects.remove(beanName);
singletonFactories.remove(beanName);
}
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory){
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
}
}
public void registerDisposableBean(String beanName, DisposableBean bean) {
disposableBeans.put(beanName, bean);
}
public void destroySingletons() {
Set<String> keySet = this.disposableBeans.keySet();
Object[] disposableBeanNames = keySet.toArray();
for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
Object beanName = disposableBeanNames[i];
DisposableBean disposableBean = disposableBeans.remove(beanName);
try {
disposableBean.destroy();
} catch (Exception e) {
throw new BeansException("Destroy method on bean with name '" + beanName + "' threw an exception", e);
}
}
}
}
|
2302_77879529/spring
|
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java
|
Java
|
apache-2.0
| 4,021
|