proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-annotatedBeanDefinitionReader/src/main/java/com/xcs/spring/AnnotatedBeanDefinitionReaderDemo.java
|
AnnotatedBeanDefinitionReaderDemo
|
main
|
class AnnotatedBeanDefinitionReaderDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个 AnnotationConfigApplicationContext
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
// 创建 AnnotatedBeanDefinitionReader 并将其关联到容器
AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(factory);
// 使用 AnnotatedBeanDefinitionReader 注册Bean对象
reader.registerBean(MyBean.class);
// 获取并打印 MyBean
System.out.println("MyBean = " + factory.getBean(MyBean.class));
| 38
| 132
| 170
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-beanDefinition/src/main/java/com/xcs/spring/BeanDefinitionDemo.java
|
BeanDefinitionDemo
|
main
|
class BeanDefinitionDemo {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
private static BeanDefinition createBeanDefinition() throws IOException {
SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(MyBean.class.getName());
ScannedGenericBeanDefinition beanDefinition = new ScannedGenericBeanDefinition(metadataReader);
beanDefinition.setScope("singleton");
beanDefinition.setLazyInit(true);
beanDefinition.setPrimary(true);
beanDefinition.setAbstract(false);
beanDefinition.setInitMethodName("init");
beanDefinition.setDestroyMethodName("destroy");
beanDefinition.setAutowireCandidate(true);
beanDefinition.setRole(BeanDefinition.ROLE_APPLICATION);
beanDefinition.setDescription("This is a custom bean definition");
beanDefinition.setResourceDescription("com.xcs.spring.BeanDefinitionDemo");
beanDefinition.getPropertyValues().add("name", "lex");
beanDefinition.getPropertyValues().add("age", "18");
return beanDefinition;
}
}
|
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerBeanDefinition("myBean", createBeanDefinition());
// 获取MyBean
MyBean myChildBean = beanFactory.getBean("myBean", MyBean.class);
// 打印Bean对象
System.out.println("MyBean = " + myChildBean);
// 销毁myBean
beanFactory.destroySingleton("myBean");
| 289
| 111
| 400
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-beanDefinition/src/main/java/com/xcs/spring/bean/MyBean.java
|
MyBean
|
toString
|
class MyBean {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public void init(){
System.out.println("execute com.xcs.spring.bean.MyBean.init");
}
public void destroy(){
System.out.println("execute com.xcs.spring.bean.MyBean.destroy");
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MyBean{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
| 194
| 40
| 234
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-beanDefinitionHolder/src/main/java/com/xcs/spring/BeanDefinitionHolderDemo.java
|
BeanDefinitionHolderDemo
|
main
|
class BeanDefinitionHolderDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个 DefaultListableBeanFactory,它是 BeanDefinitionRegistry 的一个实现
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// 创建一个新的 BeanDefinition 对象
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(MyBean.class);
// Bean名称
String beanName = "myBean";
// 设置别名(aliases)
String[] aliases = {"myBeanX", "myBeanY"};
// 创建一个 BeanDefinitionHolder,将 BeanDefinition 与名称关联起来
BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName, aliases);
// 使用 BeanDefinitionReaderUtils 注册 BeanDefinitionHolder
BeanDefinitionReaderUtils.registerBeanDefinition(beanDefinitionHolder, beanFactory);
System.out.println("myBean = " + beanFactory.getBean("myBean"));
System.out.println("myBeanX = " + beanFactory.getBean("myBeanX"));
System.out.println("myBeanY = " + beanFactory.getBean("myBeanY"));
| 36
| 286
| 322
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-beanDefinitionRegistry/src/main/java/com/xcs/spring/BeanDefinitionRegistryDemo.java
|
BeanDefinitionRegistryDemo
|
main
|
class BeanDefinitionRegistryDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个BeanFactory,它是BeanDefinitionRegistry
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// 创建一个Bean定义
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(MyBean.class);
// 注册Bean定义到BeanFactory
beanFactory.registerBeanDefinition("myBean", beanDefinition);
// 获取BeanDefinition
BeanDefinition retrievedBeanDefinition = beanFactory.getBeanDefinition("myBean");
System.out.println("Bean定义的类名 = " + retrievedBeanDefinition.getBeanClassName());
// 检查Bean定义是否存在
boolean containsBeanDefinition = beanFactory.containsBeanDefinition("myBean");
System.out.println("Bean定义是否包含(myBean) = " + containsBeanDefinition);
// 获取所有Bean定义的名称
String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
System.out.println("Bean定义的名称 = " + String.join(", ", beanDefinitionNames));
// 获取Bean定义的数量
int beanDefinitionCount = beanFactory.getBeanDefinitionCount();
System.out.println("Bean定义的数量 = " + beanDefinitionCount);
// 检查Bean名称是否已被使用
boolean isBeanNameInUse = beanFactory.isBeanNameInUse("myBean");
System.out.println("Bean名称(myBean)是否被使用 = " + isBeanNameInUse);
// 移除Bean定义
beanFactory.removeBeanDefinition("myBean");
System.out.println("Bean定义已被移除(myBean)");
| 36
| 412
| 448
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-classPathBeanDefinitionScanner/src/main/java/com/xcs/spring/ClassPathBeanDefinitionScannerDemo.java
|
ClassPathBeanDefinitionScannerDemo
|
main
|
class ClassPathBeanDefinitionScannerDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个 AnnotationConfigApplicationContext
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
// 创建 ClassPathBeanDefinitionScanner 并将其关联到容器
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(factory);
// 使用 ClassPathBeanDefinitionScanner的scan方法扫描Bean对象
scanner.scan("com.xcs.spring");
System.out.println("MyController = " + factory.getBean(MyController.class));
System.out.println("MyService = " + factory.getBean(MyService.class));
System.out.println("MyRepository = " + factory.getBean(MyRepository.class));
| 38
| 174
| 212
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-groovyBeanDefinitionReader/src/main/java/com/xcs/spring/GroovyBeanDefinitionReaderDemo.java
|
GroovyBeanDefinitionReaderDemo
|
main
|
class GroovyBeanDefinitionReaderDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个 Spring IOC 容器
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
// 创建一个 GroovyBeanDefinitionReader
GroovyBeanDefinitionReader reader = new GroovyBeanDefinitionReader(factory);
// 加载 Groovy 文件并注册 Bean 定义
reader.loadBeanDefinitions(new ClassPathResource("my-beans.groovy"));
// 获取MyService
MyService myService = factory.getBean(MyService.class);
// 打印消息
myService.showMessage();
| 38
| 146
| 184
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-propertiesBeanDefinitionReader/src/main/java/com/xcs/spring/PropertiesBeanDefinitionReaderDemo.java
|
PropertiesBeanDefinitionReaderDemo
|
main
|
class PropertiesBeanDefinitionReaderDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(beanFactory);
// 从properties文件加载bean定义
reader.loadBeanDefinitions(new ClassPathResource("bean-definitions.properties"));
// 获取bean
System.out.println("myBean = " + beanFactory.getBean("myBean"));
System.out.println("myBean = " + beanFactory.getBean("myBean"));
| 36
| 123
| 159
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-propertiesBeanDefinitionReader/src/main/java/com/xcs/spring/bean/MyBean.java
|
MyBean
|
toString
|
class MyBean {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MyBean{" +
"message='" + message + '\'' +
", hashCode='0x" + Integer.toHexString(System.identityHashCode(this)).toUpperCase() + '\'' +
'}';
| 79
| 63
| 142
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-xmlBeanDefinitionReader/src/main/java/com/xcs/spring/XmlBeanDefinitionReaderDemo.java
|
XmlBeanDefinitionReaderDemo
|
main
|
class XmlBeanDefinitionReaderDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个DefaultListableBeanFactory作为Spring容器
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
// 创建XmlBeanDefinitionReader实例用于解析XML配置
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
// 加载XML配置文件
reader.loadBeanDefinitions(new ClassPathResource("beans.xml"));
// 获取并使用Bean
MyBean myBean = factory.getBean("myBean", MyBean.class);
System.out.println("myBean = " + myBean);
| 37
| 143
| 180
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-beans/spring-bean-xmlBeanDefinitionReader/src/main/java/com/xcs/spring/bean/MyBean.java
|
MyBean
|
toString
|
class MyBean {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MyBean{" +
"message='" + message + '\'' +
'}';
| 79
| 28
| 107
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-context/spring-context-annotationConfigApplicationContext/src/main/java/com/xcs/spring/AnnotationConfigApplicationContextDemo.java
|
AnnotationConfigApplicationContextDemo
|
main
|
class AnnotationConfigApplicationContextDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 注册Bean
context.register(MyBean.class);
// 扫描包
context.scan("com.xcs.spring");
// 打印Bean定义
for (String beanDefinitionName : context.getBeanDefinitionNames()) {
System.out.println("beanDefinitionName = " + beanDefinitionName);
}
| 37
| 103
| 140
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-context/spring-context-classPathXmlApplicationContext/src/main/java/com/xcs/spring/ClassPathXmlApplicationContextDemo.java
|
ClassPathXmlApplicationContextDemo
|
main
|
class ClassPathXmlApplicationContextDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml");
System.out.println("MyBean = " + context.getBean(MyBean.class));
| 37
| 49
| 86
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-core/spring-core-destroyBean/src/main/java/com/xcs/spring/DestroyBeanApplication.java
|
DestroyBeanApplication
|
main
|
class DestroyBeanApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个基于注解的应用程序上下文对象
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 注册配置类 MyBean,告诉 Spring 在容器中管理这个配置类所定义的 bean
context.register(MyBean.class);
// 刷新应用程序上下文,初始化并启动 Spring 容器
context.refresh();
// 关闭应用程序上下文,销毁 Spring 容器并释放资源
context.close();
| 34
| 124
| 158
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-core/spring-core-getBean/src/main/java/com/xcs/spring/GetBeanApplication.java
|
GetBeanApplication
|
main
|
class GetBeanApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
System.out.println("myServiceA = " + context.getBean("myServiceA"));
System.out.println("myServiceB = " + context.getBean("myServiceB"));
| 33
| 70
| 103
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-core/spring-core-registerBeanDefinition/src/main/java/com/xcs/spring/RegisterBeanDefinitionApplication.java
|
RegisterBeanDefinitionApplication
|
main
|
class RegisterBeanDefinitionApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 注册Bean
context.register(MyBean.class);
// 扫描包
context.scan("com.xcs.spring");
// 打印Bean定义
for (String beanDefinitionName : context.getBeanDefinitionNames()) {
System.out.println("beanDefinitionName = " + beanDefinitionName);
}
| 34
| 103
| 137
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-core/spring-core-resolveDependency/src/main/java/com/xcs/spring/ResolveDependencyApplication.java
|
ResolveDependencyApplication
|
methodResolveDependency
|
class ResolveDependencyApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
// 获得Bean工厂
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
// 被注入对象
MyServiceB injectTarget = new MyServiceB();
System.out.println("Before MyServiceB = " + injectTarget + "\n");
methodResolveDependency(beanFactory, injectTarget, "setMethodMyServiceA");
fieldResolveDependency(beanFactory, injectTarget, "fieldMyServiceA");
fieldResolveDependency(beanFactory, injectTarget, "myPropertyValue");
System.out.println("After MyServiceB = " + injectTarget + "\n");
}
/**
* 解析方法依赖
*
* @param beanFactory
* @param injectTarget
*/
public static void methodResolveDependency(ConfigurableListableBeanFactory beanFactory, Object injectTarget, String name) {<FILL_FUNCTION_BODY>}
/**
* 解析字段依赖
*
* @param beanFactory
* @param injectTarget
*/
public static void fieldResolveDependency(ConfigurableListableBeanFactory beanFactory, Object injectTarget, String name) {
try {
// 1. 获取MyServiceB类中名为fieldMyServiceA的字段的引用
Field field = injectTarget.getClass().getDeclaredField(name);
// 2. 创建一个描述此字段的DependencyDescriptor
DependencyDescriptor desc = new DependencyDescriptor(field, true);
// 3. 使用BeanFactory来解析这个字段的依赖
Object value = beanFactory.resolveDependency(desc, null);
System.out.println("解析字段依赖结果:");
System.out.println("---------------------------------------------");
System.out.println(String.format("Name: %s.%s", field.getDeclaringClass().getName(), field.getName()));
System.out.println(String.format("Value: %s", value));
System.out.println("---------------------------------------------\n");
// 4. 使字段可访问(特别是如果它是private的)
ReflectionUtils.makeAccessible(field);
// 5. 使用反射设置这个字段的值,将解析得到的依赖注入到目标对象中
field.set(injectTarget, value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
try {
// 1. 获取MyServiceB类中名为setMyServiceA的方法的引用
Method method = injectTarget.getClass().getMethod(name, MyServiceA.class);
// 2. 创建一个描述此方法参数的DependencyDescriptor
DependencyDescriptor desc = new DependencyDescriptor(new MethodParameter(method, 0), true);
// 3. 使用BeanFactory来解析这个方法参数的依赖
Object value = beanFactory.resolveDependency(desc, null);
System.out.println("解析方法依赖结果:");
System.out.println("---------------------------------------------");
System.out.println(String.format("Name: %s.%s",method.getDeclaringClass().getName(),method.getName()));
System.out.println(String.format("Value: %s", value));
System.out.println("---------------------------------------------\n");
// 4. 使方法可访问(特别是如果它是private的)
ReflectionUtils.makeAccessible(method);
// 5. 使用反射调用这个方法,将解析得到的依赖注入到目标对象中
method.invoke(injectTarget, value);
} catch (Exception e) {
e.printStackTrace();
}
| 643
| 321
| 964
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-core/spring-core-resolveDependency/src/main/java/com/xcs/spring/service/MyServiceB.java
|
MyServiceB
|
toString
|
class MyServiceB {
/**
* 方法注入
*/
private MyServiceA methodMyServiceA;
/**
* 字段注入
*/
private MyServiceA fieldMyServiceA;
/**
* 字段注入 (环境变量)
*/
@Value("${my.property.value}")
private String myPropertyValue;
public void setMethodMyServiceA(MyServiceA methodMyServiceA){
this.methodMyServiceA = methodMyServiceA;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MyServiceB{" +
"myPropertyValue='" + myPropertyValue + '\'' +
", methodMyServiceA=" + methodMyServiceA +
", fieldMyServiceA=" + fieldMyServiceA +
'}';
| 162
| 63
| 225
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-conditionalConverter/src/main/java/com/xcs/spring/ConditionalConverterDemo.java
|
ConditionalConverterDemo
|
main
|
class ConditionalConverterDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建自定义的转换器实例
StringToIntegerConditionalConverter converter = new StringToIntegerConditionalConverter();
// 定义源类型(String)和目标类型(Integer)的描述符
TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class);
TypeDescriptor targetType = TypeDescriptor.valueOf(Integer.class);
// 测试转换器是否适用于从 String 到 Integer 的转换
if (converter.matches(sourceType, targetType)) {
// 如果转换条件匹配,则执行转换
Integer result = converter.convert("8");
System.out.println("Converted result: " + result);
} else {
// 如果条件不匹配,打印不适用的消息
System.out.println("Conversion not applicable.");
}
| 35
| 212
| 247
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-conditionalConverter/src/main/java/com/xcs/spring/converter/StringToIntegerConditionalConverter.java
|
StringToIntegerConditionalConverter
|
convert
|
class StringToIntegerConditionalConverter implements Converter<String, Integer>, ConditionalConverter {
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
// 判断条件:当源类型是 String 且目标类型是 Integer 时返回 true
return String.class.equals(sourceType.getType()) && Integer.class.equals(targetType.getType());
}
@Override
public Integer convert(String source) {<FILL_FUNCTION_BODY>}
}
|
if (source == null || source.isEmpty()) {
return null;
}
try {
return Integer.parseInt(source);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Unable to convert String to Integer: " + source, e);
}
| 127
| 73
| 200
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-conversionService/src/main/java/com/xcs/spring/ConversionServiceDemo.java
|
ConversionServiceDemo
|
main
|
class ConversionServiceDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建 DefaultConversionService 实例
ConversionService conversionService = new DefaultConversionService();
// 使用 canConvert 检查转换是否可能
if (conversionService.canConvert(Integer.class, String.class)) {
System.out.println("Can convert from Integer to String");
// 执行转换操作,将 Integer 转换为 String
String converted = conversionService.convert(666, String.class);
System.out.println("Converted: " + converted);
}
// 使用 TypeDescriptor 检查转换是否可能
if (conversionService.canConvert(
TypeDescriptor.valueOf(Integer.class),
TypeDescriptor.valueOf(String.class))) {
System.out.println("Can convert from Integer to String using TypeDescriptors");
// 使用 TypeDescriptor 执行转换
Object convertedWithTypeDescriptor = conversionService.convert(
888,
TypeDescriptor.valueOf(Integer.class),
TypeDescriptor.valueOf(String.class));
System.out.println("Converted with TypeDescriptors: " + convertedWithTypeDescriptor);
}
| 35
| 282
| 317
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-converter/src/main/java/com/xcs/spring/ConverterDemo.java
|
ConverterDemo
|
main
|
class ConverterDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个默认的转换服务
DefaultConversionService service = new DefaultConversionService();
// 向服务中添加自定义的转换器
service.addConverter(new StringToLocalDateConverter());
service.addConverter(new StringToBooleanConverter());
// 检查是否可以将字符串转换为 LocalDate
if (service.canConvert(String.class, LocalDate.class)) {
LocalDate localDate = service.convert("2023-12-07", LocalDate.class);
System.out.println("LocalDate = " + localDate);
}
// 检查是否可以将字符串 "yes" 转换为 Boolean
if (service.canConvert(String.class, Boolean.class)) {
Boolean boolValue = service.convert("yes", Boolean.class);
System.out.println("yes = " + boolValue);
}
// 检查是否可以将字符串 "no" 转换为 Boolean
if (service.canConvert(String.class, Boolean.class)) {
Boolean boolValue = service.convert("no", Boolean.class);
System.out.println("no = " + boolValue);
}
| 34
| 298
| 332
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-converter/src/main/java/com/xcs/spring/converter/StringToBooleanConverter.java
|
StringToBooleanConverter
|
convert
|
class StringToBooleanConverter implements Converter<String, Boolean> {
private static final Set<String> trueValues = new HashSet<>(8);
private static final Set<String> falseValues = new HashSet<>(8);
static {
trueValues.add("true");
trueValues.add("on");
trueValues.add("yes");
trueValues.add("1");
falseValues.add("false");
falseValues.add("off");
falseValues.add("no");
falseValues.add("0");
}
@Override
@Nullable
public Boolean convert(String source) {<FILL_FUNCTION_BODY>}
}
|
if (trueValues.contains(source)) {
return Boolean.TRUE;
}
if (falseValues.contains(source)) {
return Boolean.FALSE;
}
throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
| 169
| 63
| 232
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-converterFactory/src/main/java/com/xcs/spring/CharacterToNumberFactoryDemo.java
|
CharacterToNumberFactoryDemo
|
main
|
class CharacterToNumberFactoryDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个默认的转换服务
// 这里使用 GenericConversionService,它是一个通用的类型转换服务
GenericConversionService conversionService = new DefaultConversionService();
// 向转换服务中添加一个字符串到数字的转换器工厂
// StringToNumberConverterFactory 是一个工厂类,用于创建字符串到数字的转换器
conversionService.addConverterFactory(new StringToNumberConverterFactory());
// 使用转换服务将字符串 "8" 转换为 Integer 类型
// 这里演示了如何将字符串转换为对应的整数
Integer num = conversionService.convert("8", Integer.class);
// 输出转换结果
System.out.println("String to Integer: " + num);
| 39
| 213
| 252
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-genericConverter/src/main/java/com/xcs/spring/GenericConverterDemo.java
|
GenericConverterDemo
|
main
|
class GenericConverterDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个默认的转换服务
DefaultConversionService service = new DefaultConversionService();
// 向转换服务中添加自定义的转换器
service.addConverter(new AnnotatedStringToDateConverter());
// 定义源类型和目标类型,准备将 String 转换为 Date
TypeDescriptor sourceType1 = TypeDescriptor.valueOf(String.class);
TypeDescriptor targetType1 = new TypeDescriptor(ReflectionUtils.findField(MyBean.class, "date"));
// 执行转换操作
Date date = (Date) service.convert("2023-01-01", sourceType1, targetType1);
// 定义另一组源类型和目标类型,准备将另一个 String 格式转换为 Date
TypeDescriptor sourceType2 = TypeDescriptor.valueOf(String.class);
TypeDescriptor targetType2 = new TypeDescriptor(ReflectionUtils.findField(MyBean.class, "dateTime"));
// 执行转换操作
Date dateTime = (Date) service.convert("2023-01-01 23:59:59", sourceType2, targetType2);
// 使用转换得到的日期对象设置 MyBean 实例的属性
MyBean myBean = new MyBean();
myBean.setDate(date);
myBean.setDateTime(dateTime);
// 输出转换结果
System.out.println("myBean = " + myBean);
| 38
| 392
| 430
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-genericConverter/src/main/java/com/xcs/spring/bean/MyBean.java
|
MyBean
|
toString
|
class MyBean {
@DateFormat("yyyy-MM-dd")
private Date date;
@DateFormat("yyyy-MM-dd hh:mm:ss")
private Date dateTime;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MyBean{" +
"date=" + date +
", dateTime=" + dateTime +
'}';
| 189
| 41
| 230
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-genericConverter/src/main/java/com/xcs/spring/convert/AnnotatedStringToDateConverter.java
|
AnnotatedStringToDateConverter
|
convert
|
class AnnotatedStringToDateConverter implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
// 定义可转换的类型对:从 String 到 Date
return Collections.singleton(new ConvertiblePair(String.class, Date.class));
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {<FILL_FUNCTION_BODY>}
}
|
// 如果源对象为空,直接返回 null
if (source == null) {
return null;
}
// 将源对象转换为字符串
String dateString = (String) source;
// 获取目标类型(Date类型字段)上的 DateFormat 注解
DateFormat dateFormatAnnotation = targetType.getAnnotation(DateFormat.class);
// 如果目标字段上没有 DateFormat 注解,则抛出异常
if (dateFormatAnnotation == null) {
throw new IllegalArgumentException("目标字段上缺少DateFormat注解");
}
try {
// 根据注解中提供的日期格式创建 SimpleDateFormat
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatAnnotation.value());
// 使用 SimpleDateFormat 将字符串解析为日期对象
return dateFormat.parse(dateString);
} catch (Exception e) {
// 如果解析失败,抛出异常
throw new IllegalArgumentException("无法解析日期", e);
}
| 127
| 286
| 413
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-parser/src/main/java/com/xcs/spring/ParserDemo.java
|
ParserDemo
|
main
|
class ParserDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个格式化转换服务
FormattingConversionService conversionService = new FormattingConversionService();
// 向转换服务中添加一个货币解析器
conversionService.addParser(new CurrencyParser());
// 设置当前线程的区域设置为美国
LocaleContextHolder.setLocale(Locale.US);
// 将美元格式的字符串转换为数值类型
Number formattedAmountForUS = conversionService.convert("$1,234.56", Number.class);
System.out.println("Parsed Currency (US): " + formattedAmountForUS);
// 改变区域设置为中国
LocaleContextHolder.setLocale(Locale.CHINA);
// 将人民币格式的字符串转换为数值类型
Number formattedAmountForCHINA = conversionService.convert("¥1,234.56", Number.class);
System.out.println("Parsed Currency (CHINA): " + formattedAmountForCHINA);
| 37
| 276
| 313
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-parser/src/main/java/com/xcs/spring/parser/CurrencyParser.java
|
CurrencyParser
|
parse
|
class CurrencyParser implements Parser<Number> {
@Override
public Number parse(String text, Locale locale) throws ParseException {<FILL_FUNCTION_BODY>}
}
|
// 创建适用于特定区域的货币格式化器
NumberFormat format = NumberFormat.getCurrencyInstance(locale);
// 解析字符串为数字
return format.parse(text);
| 51
| 60
| 111
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-printer/src/main/java/com/xcs/spring/PrinterDemo.java
|
PrinterDemo
|
main
|
class PrinterDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个 FormattingConversionService 实例
FormattingConversionService conversionService = new FormattingConversionService();
// 将自定义的 CurrencyPrinter 注册到 conversionService
conversionService.addPrinter(new CurrencyPrinter());
// 设置货币金额
double amount = 1234.56;
// 设置当前线程的 Locale 为美国
LocaleContextHolder.setLocale(Locale.US);
// 使用 conversionService 将金额转换为字符串,并应用美国的货币格式
String formattedAmountForUS = conversionService.convert(amount, String.class);
System.out.println("Formatted Currency (US): " + formattedAmountForUS);
// 设置当前线程的 Locale 为中国
LocaleContextHolder.setLocale(Locale.CHINA);
// 使用 conversionService 将金额转换为字符串,并应用中国的货币格式
String formattedAmountForCHINA = conversionService.convert(amount, String.class);
System.out.println("Formatted Currency (CHINA): " + formattedAmountForCHINA);
| 37
| 307
| 344
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-propertyEditor/src/main/java/com/xcs/spring/PropertyEditorDemo.java
|
PropertyEditorDemo
|
main
|
class PropertyEditorDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个 BeanWrapperImpl 实例,用于操作 MyBean 类。
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(MyBean.class);
// 为 Date 类型的属性注册自定义的属性编辑器 MyCustomDateEditor。
beanWrapper.overrideDefaultEditor(Date.class, new MyCustomDateEditor());
// 设置 MyBean 类中名为 "date" 的属性值,使用字符串 "2023-12-5"。
// 这里会使用注册的 MyCustomDateEditor 来将字符串转换为 Date 对象。
beanWrapper.setPropertyValue("date", "2023-12-5");
// 设置 MyBean 类中名为 "path" 的属性值,使用字符串 "/opt/spring-reading"。
// 因为没有为 Path 类型注册特定的编辑器,所以使用默认转换逻辑。
beanWrapper.setPropertyValue("path", "/opt/spring-reading");
// 输出最终包装的 MyBean 实例。
System.out.println("MyBean = " + beanWrapper.getWrappedInstance());
| 37
| 305
| 342
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-propertyEditor/src/main/java/com/xcs/spring/bean/MyBean.java
|
MyBean
|
toString
|
class MyBean {
private Path path;
private Date date;
public Path getPath() {
return path;
}
public void setPath(Path path) {
this.path = path;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MyBean{" +
"path=" + path +
", date=" + date +
'}';
| 150
| 39
| 189
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-validator/src/main/java/com/xcs/spring/PersonValidator.java
|
PersonValidator
|
validate
|
class PersonValidator implements Validator {
@Override
public boolean supports(Class clazz) {
return Person.class.equals(clazz);
}
@Override
public void validate(Object obj, Errors e) {<FILL_FUNCTION_BODY>}
}
|
// 检查名称是否为空
ValidationUtils.rejectIfEmpty(e, "name", "name.empty", "姓名不能为空");
// 将对象转换为 Person 类型
Person p = (Person) obj;
// 检查年龄是否为负数
if (p.getAge() < 0) {
e.rejectValue("age", "negative.value", "年龄不能为负数");
}
// 检查年龄是否超过 120 岁
else if (p.getAge() > 120) {
e.rejectValue("age", "too.darn.old", "目前年龄最大的是120岁");
}
| 72
| 176
| 248
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-dataops/spring-dataops-validator/src/main/java/com/xcs/spring/ValidatorDemo.java
|
ValidatorDemo
|
main
|
class ValidatorDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个 Person 对象实例
Person person = new Person();
person.setName(null);
person.setAge(130);
// 创建一个 BeanPropertyBindingResult 对象,用于存储验证过程中的错误
BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
// 创建一个 PersonValidator 实例,这是自定义的验证器
PersonValidator validator = new PersonValidator();
// 检查 PersonValidator 是否支持 Person 类的验证
if (validator.supports(person.getClass())) {
// 执行验证逻辑
validator.validate(person, result);
}
// 检查是否存在验证错误,并打印出所有的字段错误
if (result.hasErrors()) {
for (FieldError error : result.getFieldErrors()) {
System.out.println(error.getField() + ":" + error.getDefaultMessage());
}
}
| 34
| 247
| 281
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-env/spring-env-configurableEnvironment/src/main/java/com/xcs/spring/ConfigurableEnvironmentDemo.java
|
ConfigurableEnvironmentDemo
|
main
|
class ConfigurableEnvironmentDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建 StandardEnvironment 实例,用于访问属性和配置文件信息
ConfigurableEnvironment environment = new StandardEnvironment();
// 设置配置文件
environment.setActiveProfiles("dev");
System.out.println("Active Profiles: " + String.join(", ", environment.getActiveProfiles()));
// 添加配置文件
environment.addActiveProfile("test");
System.out.println("Updated Active Profiles: " + String.join(", ", environment.getActiveProfiles()));
// 设置默认配置文件
environment.setDefaultProfiles("default");
System.out.println("Default Profiles: " + String.join(", ", environment.getDefaultProfiles()));
// 获取系统属性
Map<String, Object> systemProperties = environment.getSystemProperties();
System.out.println("System Properties: " + systemProperties);
// 获取系统环境变量
Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
System.out.println("System Environment: " + systemEnvironment);
// 合并环境变量
Map<String, Object> properties = new HashMap<>();
properties.put("app.name", "Spring-Reading");
properties.put("app.version", "1.0.0");
StandardEnvironment standardEnvironment = new StandardEnvironment();
standardEnvironment.getPropertySources().addFirst(new MapPropertySource("myEnvironment", properties));
environment.merge(standardEnvironment);
// 获取可变属性源
MutablePropertySources propertySources = environment.getPropertySources();
System.out.println("MutablePropertySources: " + propertySources);
| 35
| 408
| 443
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-env/spring-env-configurablePropertyResolver/src/main/java/com/xcs/spring/ConfigurablePropertyResolverDemo.java
|
ConfigurablePropertyResolverDemo
|
main
|
class ConfigurablePropertyResolverDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建属性源
Map<String, Object> properties = new HashMap<>();
properties.put("app.name", "Spring-Reading");
properties.put("app.version", "1.0.0");
MapPropertySource propertySource = new MapPropertySource("myPropertySource", properties);
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addLast(propertySource);
// 创建 ConfigurablePropertyResolver
PropertySourcesPropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources);
// 设置和获取转换服务
ConfigurableConversionService conversionService = new DefaultConversionService();
propertyResolver.setConversionService(conversionService);
// 设置占位符前后缀
propertyResolver.setPlaceholderPrefix("${");
propertyResolver.setPlaceholderSuffix("}");
// 设置默认值分隔符
propertyResolver.setValueSeparator(":");
// 设置未解析占位符的处理方式
propertyResolver.setIgnoreUnresolvableNestedPlaceholders(true);
// 设置并验证必需的属性
propertyResolver.setRequiredProperties("app.name", "app.version");
propertyResolver.validateRequiredProperties();
// 读取属性
String appName = propertyResolver.getProperty("app.name");
String appVersion = propertyResolver.getProperty("app.version", String.class, "Unknown Version");
System.out.println("获取属性 app.name: " + appName);
System.out.println("获取属性 app.version: " + appVersion);
| 36
| 407
| 443
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-env/spring-env-environment/src/main/java/com/xcs/spring/EnvironmentDemo.java
|
EnvironmentDemo
|
main
|
class EnvironmentDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 设置系统属性以模拟 Spring 的配置文件功能
System.setProperty("spring.profiles.default", "dev");
System.setProperty("spring.profiles.active", "test");
// 创建 StandardEnvironment 实例,用于访问属性和配置文件信息
Environment environment = new StandardEnvironment();
// 使用 getProperty 方法获取系统属性。这里获取了 Java 版本
String javaVersion = environment.getProperty("java.version");
System.out.println("java.version: " + javaVersion);
// 获取当前激活的配置文件(profiles)
String[] activeProfiles = environment.getActiveProfiles();
System.out.println("activeProfiles = " + String.join(",", activeProfiles));
// 获取默认配置文件(当没有激活的配置文件时使用)
String[] defaultProfiles = environment.getDefaultProfiles();
System.out.println("defaultProfiles = " + String.join(",", defaultProfiles));
// 检查是否激活了指定的配置文件。这里检查的是 'test' 配置文件
boolean isDevProfileActive = environment.acceptsProfiles("test");
System.out.println("acceptsProfiles('test'): " + isDevProfileActive);
| 33
| 319
| 352
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-env/spring-env-propertyResolver/src/main/java/com/xcs/spring/SimplePropertyResolverDemo.java
|
SimplePropertyResolverDemo
|
main
|
class SimplePropertyResolverDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建属性源
Map<String, Object> properties = new HashMap<>();
properties.put("app.name", "Spring-Reading");
properties.put("app.version", "1.0.0");
properties.put("app.description", "This is a ${app.name} with version ${app.version}");
MapPropertySource propertySource = new MapPropertySource("myPropertySource", properties);
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addLast(propertySource);
// 使用 PropertySourcesPropertyResolver
PropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources);
// 获取属性
String appName = propertyResolver.getProperty("app.name");
String appVersion = propertyResolver.getProperty("app.version");
System.out.println("获取属性 app.name: " + appName);
System.out.println("获取属性 app.version: " + appVersion);
// 检查属性是否存在
boolean containsDescription = propertyResolver.containsProperty("app.description");
boolean containsReleaseDate = propertyResolver.containsProperty("app.releaseDate");
System.out.println("是否包含 'app.description' 属性: " + containsDescription);
System.out.println("是否包含 'app.releaseDate' 属性: " + containsReleaseDate);
// 带默认值的属性获取
String appReleaseDate = propertyResolver.getProperty("app.releaseDate", "2023-11-30");
System.out.println("带默认值的属性获取 app.releaseDate : " + appReleaseDate);
// 获取必需属性
String requiredAppName = propertyResolver.getRequiredProperty("app.name");
System.out.println("获取必需属性 app.name: " + requiredAppName);
// 解析占位符
String appDescription = propertyResolver.resolvePlaceholders(properties.get("app.description").toString());
System.out.println("解析占位符 app.description: " + appDescription);
// 解析必需的占位符
String requiredAppDescription = propertyResolver.resolveRequiredPlaceholders("App Description: ${app.description}");
System.out.println("解析必需的占位符 : " + requiredAppDescription);
| 35
| 578
| 613
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-env/spring-env-propertySource/src/main/java/com/xcs/spring/PropertySourceDemo.java
|
PropertySourceDemo
|
main
|
class PropertySourceDemo {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// 从 .properties 文件加载属性
Properties source = PropertiesLoaderUtils.loadProperties(new ClassPathResource("application.properties"));
PropertySource propertySource = new PropertiesPropertySource("properties", source);
// 直接从Resource加载属性
ClassPathResource classPathResource = new ClassPathResource("application.properties");
PropertySource resourcePropertySource = new ResourcePropertySource("resource", classPathResource);
// 从Map加载属性
Map<String, Object> map = new HashMap<>();
map.put("app.name", "Spring-Reading");
map.put("app.version", "1.0.0");
PropertySource mapPropertySource = new MapPropertySource("mapSource", map);
// 访问系统环境变量
Map mapEnv = System.getenv();
PropertySource envPropertySource = new SystemEnvironmentPropertySource("systemEnv", mapEnv);
// 解析命令行参数
String[] myArgs = {"--appName=MyApplication", "--port=8080"};
PropertySource commandLinePropertySource = new SimpleCommandLinePropertySource(myArgs);
// 组合多个 PropertySource 实例
CompositePropertySource composite = new CompositePropertySource("composite");
composite.addPropertySource(propertySource);
composite.addPropertySource(resourcePropertySource);
composite.addPropertySource(mapPropertySource);
composite.addPropertySource(envPropertySource);
composite.addPropertySource(commandLinePropertySource);
// 打印结果
for (PropertySource<?> ps : composite.getPropertySources()) {
System.out.printf("Name: %-15s || Source: %s%n", ps.getName(), ps.getSource());
}
| 36
| 427
| 463
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-env/spring-env-propertySources/src/main/java/com/xcs/spring/PropertySourcesDemo.java
|
PropertySourcesDemo
|
main
|
class PropertySourcesDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建 MutablePropertySources 对象
MutablePropertySources propertySources = new MutablePropertySources();
// 创建两个 MapPropertySource 对象
Map<String, Object> config1 = new HashMap<>();
config1.put("key1", "value1");
PropertySource<?> mapPropertySource1 = new MapPropertySource("config1", config1);
Map<String, Object> config2 = new HashMap<>();
config2.put("key2", "value2");
PropertySource<?> mapPropertySource2 = new MapPropertySource("config2", config2);
// 添加属性源到开头
propertySources.addFirst(mapPropertySource1);
// 添加属性源到末尾
propertySources.addLast(mapPropertySource2);
// 打印
System.out.println("打印属性源");
for (PropertySource<?> ps : propertySources) {
System.out.printf("Name: %-10s || Source: %s%n", ps.getName(), ps.getSource());
}
System.out.println();
// 替换属性源
Map<String, Object> newConfig = new HashMap<>();
newConfig.put("app.name", "Spring-Reading");
newConfig.put("app.version", "1.0.0");
PropertySource<?> newMapPropertySource = new MapPropertySource("config1", newConfig);
propertySources.replace("config1", newMapPropertySource);
// 打印替换后
System.out.println("打印替换后的属性源");
for (PropertySource<?> ps : propertySources) {
System.out.printf("Name: %-10s || Source: %s%n", ps.getName(), ps.getSource());
}
System.out.println();
// 检查是否包含属性源
System.out.println("检查是否包含属性源 config2: " + propertySources.contains("config2"));
// 移除属性源
System.out.println("移除属性源 config2: " + propertySources.remove("config2"));
// 再次检查是否包含属性源
System.out.println("删除后是否包含属性源 config2: " + propertySources.contains("config2"));
| 35
| 587
| 622
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-factory/spring-factory-autowireCapableBeanFactory/src/main/java/com/xcs/spring/AutowireCapableBeanFactoryDemo.java
|
AutowireCapableBeanFactoryDemo
|
configureBean
|
class AutowireCapableBeanFactoryDemo {
public static void main(String[] args) {
// 创建 ApplicationContext
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfiguration.class);
// 配置一个后置处理器,用于验证Bean的初始化前后拦截信息打印
applicationContext.getBeanFactory().addBeanPostProcessor(new MyBeanPostProcessor());
// 注册一个MyRepository的Bean对象
applicationContext.getBeanFactory().registerSingleton("myRepository", new MyRepository());
// 获取 AutowireCapableBeanFactory
AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
// 创建指定Bean名称的实例
// createBean(beanFactory);
// 对给定的Bean实例进行进一步的配置
// configureBean(beanFactory);
// 对给定的Bean实例进行自动装配
// autowireBean(beanFactory);
// 使用指定的自动装配模式创建Bean实例
// autowire(beanFactory);
// 对给定的Bean实例的属性进行自动装配
// autowireBeanProperties(beanFactory);
// 将属性值应用到给定的Bean实例
// applyBeanPropertyValues(beanFactory);
// 初始化给定的Bean实例
// initializeBean(beanFactory);
// 销毁给定的Bean实例
// destroyBean(beanFactory);
// 解析Bean之间的依赖关系
// resolveDependency(beanFactory);
}
private static void createBean(AutowireCapableBeanFactory beanFactory) {
MyService myService = beanFactory.createBean(MyService.class);
System.out.println("调用createBean方法,创建Bean对象 = " + myService);
}
private static void configureBean(AutowireCapableBeanFactory beanFactory) {<FILL_FUNCTION_BODY>}
private static void autowireBean(AutowireCapableBeanFactory beanFactory) {
MyService myService = new MyService();
System.out.println("调用autowireBean前,MyService = " + myService);
beanFactory.autowireBean(myService);
System.out.println("调用autowireBean后,MyService = " + myService);
}
private static void autowire(AutowireCapableBeanFactory beanFactory) {
Object myService = beanFactory.autowire(MyService.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
System.out.println("调用autowire方法,创建Bean对象 =" + myService);
}
private static void autowireBeanProperties(AutowireCapableBeanFactory beanFactory) {
MyService myService = new MyService();
System.out.println("调用autowireBeanProperties前,MyService = " + myService);
beanFactory.autowireBeanProperties(myService, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
System.out.println("调用autowireBeanProperties后,MyService = " + myService);
}
private static void applyBeanPropertyValues(AutowireCapableBeanFactory beanFactory) {
PropertyValue propertyValue = new PropertyValue("javaHome", "这里是我自定义的javaHome路径配置");
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.addPropertyValue(propertyValue);
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(MyService.class);
rootBeanDefinition.setPropertyValues(propertyValues);
// 配置一个RootBeanDefinition
((DefaultListableBeanFactory) beanFactory).registerBeanDefinition("myService", rootBeanDefinition);
MyService myService = new MyService();
System.out.println("调用applyBeanPropertyValues前,MyService = " + myService);
beanFactory.applyBeanPropertyValues(myService, "myService");
System.out.println("调用applyBeanPropertyValues后,MyService = " + myService);
}
private static void initializeBean(AutowireCapableBeanFactory beanFactory) {
MyService myService = new MyService();
System.out.println("调用initializeBean前,MyService = " + myService);
beanFactory.initializeBean(myService, "myService");
System.out.println("调用initializeBean前,MyService = " + myService);
}
private static void destroyBean(AutowireCapableBeanFactory beanFactory) {
beanFactory.destroyBean(new MyService());
}
private static void resolveDependency(AutowireCapableBeanFactory beanFactory) {
try {
DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(MyService.class.getDeclaredField("myRepository"), false);
Object resolveDependency = beanFactory.resolveDependency(dependencyDescriptor, "myRepository");
System.out.println("resolveDependency = " + resolveDependency);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
|
// 配置一个RootBeanDefinition
((DefaultListableBeanFactory) beanFactory).registerBeanDefinition("myService", new RootBeanDefinition(MyService.class));
MyService myService = new MyService();
System.out.println("调用configureBean前,MyService = " + myService);
beanFactory.configureBean(myService, "myService");
System.out.println("调用configureBean后,MyService = " + myService);
| 1,262
| 112
| 1,374
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-factory/spring-factory-autowireCapableBeanFactory/src/main/java/com/xcs/spring/service/MyService.java
|
MyService
|
toString
|
class MyService implements BeanNameAware, InitializingBean, DisposableBean {
@Autowired
private MyRepository myRepository;
@Value("${java.home}")
private String javaHome;
@Override
public void setBeanName(String name) {
System.out.println("MyService.setBeanName方法被调用了");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("MyService.afterPropertiesSet方法被调用了");
}
@Override
public void destroy() throws Exception {
System.out.println("MyService.destroy方法被调用了");
}
public void setJavaHome(String javaHome) {
this.javaHome = javaHome;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MyService{" +
"myRepository=" + myRepository +
", javaHome='" + javaHome + '\'' +
'}';
| 220
| 41
| 261
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-factory/spring-factory-beanFactory/src/main/java/com/xcs/spring/BeanFactoryDemo.java
|
BeanFactoryDemo
|
main
|
class BeanFactoryDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建 BeanFactory
BeanFactory beanFactory = new AnnotationConfigApplicationContext(MyBean.class).getBeanFactory();
// 根据名称获取 bean
Object bean = beanFactory.getBean("myBean");
System.out.println("通过名称获取Bean: " + bean);
// 获取 bean 的 ObjectProvider
ObjectProvider<MyBean> objectProvider = beanFactory.getBeanProvider(MyBean.class);
System.out.println("获取Bean的ObjectProvider: " + objectProvider);
// 获取 bean 的类型
Class<?> beanType = beanFactory.getType("myBean");
System.out.println("获取Bean的类型: " + beanType);
// 判断是否包含某个 bean
boolean containsBean = beanFactory.containsBean("myBean");
System.out.println("判断是否包含Bean: " + containsBean);
// 判断 bean 是否为单例
boolean isSingleton = beanFactory.isSingleton("myBean");
System.out.println("判断是否为单例: " + isSingleton);
// 判断 bean 是否为原型
boolean isPrototype = beanFactory.isPrototype("myBean");
System.out.println("判断是否为原型: " + isPrototype);
// 判断 bean 是否匹配指定类型
boolean isTypeMatch = beanFactory.isTypeMatch("myBean", ResolvableType.forClass(MyBean.class));
System.out.println("判断是否匹配指定类型: " + isTypeMatch);
// 获取 bean 的所有别名
String[] aliases = beanFactory.getAliases("myBean");
System.out.println("获取Bean的所有别名: " + String.join(", ", aliases));
| 35
| 439
| 474
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-factory/spring-factory-configurableBeanFactory/src/main/java/com/xcs/spring/ConfigurableBeanFactoryDemo.java
|
ConfigurableBeanFactoryDemo
|
main
|
class ConfigurableBeanFactoryDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建 ApplicationContext
ConfigurableBeanFactory configurableBeanFactory = new AnnotationConfigApplicationContext(MyConfiguration.class).getBeanFactory();
// 设置父级 BeanFactory
configurableBeanFactory.setParentBeanFactory(new DefaultListableBeanFactory());
// 获取BeanPostProcessor数量
int beanPostProcessorCount = configurableBeanFactory.getBeanPostProcessorCount();
System.out.println("获取BeanPostProcessor数量: " + beanPostProcessorCount);
// 获取所有已注册的 Scope 名称
String[] scopeNames = configurableBeanFactory.getRegisteredScopeNames();
System.out.println("获取所有已注册的Scope名称: " + String.join(", ", scopeNames));
// 获取注册的 Scope
Scope customScope = configurableBeanFactory.getRegisteredScope("customScope");
System.out.println("获取注册的Scope :" + customScope);
// 获取ApplicationStartup
ApplicationStartup applicationStartup = configurableBeanFactory.getApplicationStartup();
System.out.println("获取ApplicationStartup: " + applicationStartup);
// 获取AccessControlContext
AccessControlContext accessControlContext = configurableBeanFactory.getAccessControlContext();
System.out.println("获取AccessControlContext: " + accessControlContext);
// 拷贝配置
ConfigurableListableBeanFactory otherFactory = new DefaultListableBeanFactory();
configurableBeanFactory.copyConfigurationFrom(otherFactory);
System.out.println("拷贝配置copyConfigurationFrom: " + otherFactory);
// 注册别名
String beanName = "myService";
String alias = "helloService";
configurableBeanFactory.registerAlias(beanName, alias);
System.out.println("注册别名registerAlias, BeanName: " + beanName + "alias: " + alias);
// 获取合并后的 BeanDefinition
BeanDefinition mergedBeanDefinition = configurableBeanFactory.getMergedBeanDefinition("myService");
System.out.println("获取合并后的 BeanDefinition: " + mergedBeanDefinition);
// 判断是否为 FactoryBean
String factoryBeanName = "myService";
boolean isFactoryBean = configurableBeanFactory.isFactoryBean(factoryBeanName);
System.out.println("判断是否为FactoryBean" + isFactoryBean);
// 设置当前 Bean 是否正在创建
String currentBeanName = "myService";
boolean inCreation = true;
configurableBeanFactory.setCurrentlyInCreation(currentBeanName, inCreation);
System.out.println("设置当前Bean是否正在创建: " + currentBeanName);
// 判断指定的 Bean 是否正在创建
boolean isCurrentlyInCreation = configurableBeanFactory.isCurrentlyInCreation(currentBeanName);
System.out.println("判断指定的Bean是否正在创建" + isCurrentlyInCreation);
// 注册依赖关系
String dependentBeanName = "dependentBean";
configurableBeanFactory.registerDependentBean(beanName, dependentBeanName);
System.out.println("注册依赖关系" + "beanName: " + beanName + "dependentBeanName: " + dependentBeanName);
// 获取所有依赖于指定 Bean 的 Bean 名称
String[] dependentBeans = configurableBeanFactory.getDependentBeans(beanName);
System.out.println("获取所有依赖于指定Bean的Bean名称: " + String.join(", ", dependentBeans));
// 获取指定 Bean 依赖的所有 Bean 名称
String[] dependencies = configurableBeanFactory.getDependenciesForBean(beanName);
System.out.println("获取指定Bean依赖的所有Bean名称: " + String.join(", ", dependencies));
// 销毁指定 Bean 实例
Object beanInstance = configurableBeanFactory.getBean(beanName);
configurableBeanFactory.destroyBean(beanName, beanInstance);
System.out.println("销毁指定 Bean 实例: " + beanName);
// 销毁所有单例 Bean
configurableBeanFactory.destroySingletons();
System.out.println("销毁所有单例Bean destroySingletons" );
| 37
| 1,047
| 1,084
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-factory/spring-factory-configurableListableBeanFactory/src/main/java/com/xcs/spring/ConfigurableListableBeanFactoryDemo.java
|
ConfigurableListableBeanFactoryDemo
|
main
|
class ConfigurableListableBeanFactoryDemo {
public static void main(String[] args) throws NoSuchFieldException {<FILL_FUNCTION_BODY>}
}
|
// 创建 ApplicationContext
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfiguration.class);
// 获取 ConfigurableListableBeanFactory
ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
// 忽略指定类型的依赖
beanFactory.ignoreDependencyType(String.class);
// 忽略指定接口的依赖
beanFactory.ignoreDependencyInterface(BeanFactory.class);
// 注册可解析的依赖
beanFactory.registerResolvableDependency(ApplicationContext.class, applicationContext);
// 判断指定的 Bean 是否可以作为自动注入的候选者
String beanName = "myService";
DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(MyController.class.getDeclaredField("myService"), false);
boolean isAutowireCandidate = beanFactory.isAutowireCandidate(beanName, dependencyDescriptor);
System.out.println(beanName + " 是否为自动注入的候选者: " + isAutowireCandidate);
// 获取指定 Bean 的 BeanDefinition
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
System.out.println(beanName + " 的 BeanDefinition: " + beanDefinition);
// 获取所有 Bean 的名称的迭代器
Iterator<String> beanNamesIterator = beanFactory.getBeanNamesIterator();
System.out.print("所有 Bean 的名称: ");
beanNamesIterator.forEachRemaining(System.out::print);
// 清除元数据缓存
beanFactory.clearMetadataCache();
// 冻结配置
beanFactory.freezeConfiguration();
// 判断配置是否已冻结
boolean isConfigurationFrozen = beanFactory.isConfigurationFrozen();
System.out.println("配置是否已冻结: " + isConfigurationFrozen);
// 预实例化所有非懒加载的单例 Bean
beanFactory.preInstantiateSingletons();
| 43
| 512
| 555
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-factory/spring-factory-hierarchicalBeanFactory/src/main/java/com/xcs/spring/HierarchicalBeanFactoryDemo.java
|
HierarchicalBeanFactoryDemo
|
main
|
class HierarchicalBeanFactoryDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建父级容器
AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext(MyBean.class);
// 创建子级容器
AnnotationConfigApplicationContext childContext = new AnnotationConfigApplicationContext();
childContext.setParent(parentContext);
// 在子级 BeanFactory 中获取 bean
HierarchicalBeanFactory childHierarchicalBeanFactory = childContext.getBeanFactory();
System.out.println("在子级BeanFactory中获取Bean: " + childHierarchicalBeanFactory.getBean(MyBean.class));
// 在父级 BeanFactory 中获取 bean
HierarchicalBeanFactory parentHierarchicalBeanFactory = parentContext.getBeanFactory();
System.out.println("在父级BeanFactory中获取Bean: " + parentHierarchicalBeanFactory.getBean(MyBean.class));
// 获取父级 BeanFactory
BeanFactory parentBeanFactory = childHierarchicalBeanFactory.getParentBeanFactory();
System.out.println("获取父级BeanFactory: " + parentBeanFactory);
// 判断本地 BeanFactory 是否包含指定名称的 bean
boolean containsLocalBean = childHierarchicalBeanFactory.containsLocalBean("myBean");
System.out.println("判断本地BeanFactory是否包含指定名称的Bean: " + containsLocalBean);
// 判断整个 BeanFactory 是否包含指定名称的 bean
boolean containsBean = childHierarchicalBeanFactory.containsBean("myBean");
System.out.println("判断整个BeanFactory是否包含指定名称的Bean: " + containsBean);
| 37
| 396
| 433
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-factory/spring-factory-listableBeanFactory/src/main/java/com/xcs/spring/ListableBeanFactoryDemo.java
|
ListableBeanFactoryDemo
|
main
|
class ListableBeanFactoryDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建 ListableBeanFactory
ListableBeanFactory beanFactory = new AnnotationConfigApplicationContext(MyConfiguration.class).getBeanFactory();
// 判断是否包含指定名称的 bean 定义
boolean containsBeanDefinition = beanFactory.containsBeanDefinition("myService");
System.out.println("判断是否包含指定名称的Bean定义: " + containsBeanDefinition);
// 获取工厂中所有 bean 定义的数量
int beanDefinitionCount = beanFactory.getBeanDefinitionCount();
System.out.println("获取工厂中所有Bean定义数量: " + beanDefinitionCount);
// 获取工厂中所有 bean 定义的名称数组
String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
System.out.println("获取工厂中所有Bean定义名称: " + String.join(", ", beanDefinitionNames));
// 获取 ObjectProvider,并懒加载获取 bean 实例
ObjectProvider<MyService> objectProvider = beanFactory.getBeanProvider(MyService.class, true);
System.out.println("获取Bean的ObjectProvider: " + objectProvider.getObject());
// 根据类型获取所有 bean 的名称
String[] beanNamesForType = beanFactory.getBeanNamesForType(ResolvableType.forClass(MyService.class));
System.out.println("根据类型获取Bean名称: " + String.join(", ", beanNamesForType));
// 根据注解类型获取所有 bean 的名称
String[] beanNamesForAnnotation = beanFactory.getBeanNamesForAnnotation(Service.class);
System.out.println("根据注解获取Bean名称: " + String.join(", ", beanNamesForAnnotation));
// 根据注解类型获取所有 bean 实例
Map<String, Object> beansWithAnnotation = beanFactory.getBeansWithAnnotation(Service.class);
System.out.println("根据注解类型获取所有Bean实例: " + beansWithAnnotation);
// 在指定 bean 上查找指定类型的注解
Service annotation = beanFactory.findAnnotationOnBean("myService", Service.class);
System.out.println("指定Bean上查找指定类型的注解: " + annotation);
| 36
| 546
| 582
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-beanDefinitionRegistryPostProcessor/src/main/java/com/xcs/spring/BeanDefinitionRegistryPostProcessorApplication.java
|
BeanDefinitionRegistryPostProcessorApplication
|
main
|
class BeanDefinitionRegistryPostProcessorApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MySimpleBean mySimpleBean1 = context.getBean(MySimpleBean.class);
mySimpleBean1.show();
| 37
| 54
| 91
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-beanDefinitionRegistryPostProcessor/src/main/java/com/xcs/spring/config/MyBeanDefinitionRegistryPostProcessor.java
|
MyBeanDefinitionRegistryPostProcessor
|
postProcessBeanDefinitionRegistry
|
class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {<FILL_FUNCTION_BODY>}
}
|
System.out.println("开始新增Bean定义");
// 创建一个新的 BeanDefinition 对象
BeanDefinition beanDefinition = new RootBeanDefinition(MySimpleBean.class);
// 使用 registry 来注册这个新的 bean 定义
registry.registerBeanDefinition("mySimpleBean", beanDefinition);
System.out.println("完成新增Bean定义");
| 87
| 92
| 179
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-beanFactoryPostProcessor/src/main/java/com/xcs/spring/BeanFactoryPostProcessorApplication.java
|
BeanFactoryPostProcessorApplication
|
main
|
class BeanFactoryPostProcessorApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MySimpleBean mySimpleBean1 = context.getBean(MySimpleBean.class);
MySimpleBean mySimpleBean2 = context.getBean(MySimpleBean.class);
mySimpleBean1.show();
mySimpleBean2.show();
| 36
| 86
| 122
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-beanPostProcessor/src/main/java/com/xcs/spring/BeanPostProcessorApplication.java
|
BeanPostProcessorApplication
|
main
|
class BeanPostProcessorApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MyService myService = context.getBean(MyService.class);
System.out.println(myService.show());
context.close();
| 35
| 60
| 95
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-beanPostProcessor/src/main/java/com/xcs/spring/config/MyBeanPostProcessor.java
|
MyBeanPostProcessor
|
postProcessAfterInitialization
|
class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof MyServiceImpl) {
MyServiceImpl myService = (MyServiceImpl) bean;
myService.setMessage("Prefix: " + myService.getMessage());
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>}
}
|
if(bean instanceof MyServiceImpl) {
MyServiceImpl myService = (MyServiceImpl) bean;
myService.setMessage(myService.getMessage() + " :Suffix");
}
return bean;
| 134
| 57
| 191
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-destructionAwareBeanPostProcessor/src/main/java/com/xcs/spring/DestructionAwareBeanPostProcessorApplication.java
|
DestructionAwareBeanPostProcessorApplication
|
main
|
class DestructionAwareBeanPostProcessorApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
ConnectionService connection = context.getBean("connectionService", ConnectionService.class);
System.out.println("Is connected: " + connection.isConnected());
context.close();
| 38
| 68
| 106
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-destructionAwareBeanPostProcessor/src/main/java/com/xcs/spring/config/MyDestructionAwareBeanPostProcessor.java
|
MyDestructionAwareBeanPostProcessor
|
postProcessAfterInitialization
|
class MyDestructionAwareBeanPostProcessor implements DestructionAwareBeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>}
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
if (bean instanceof ConnectionServiceImpl) {
((ConnectionServiceImpl) bean).closeConnection();
}
}
@Override
public boolean requiresDestruction(Object bean) {
return (bean instanceof ConnectionServiceImpl);
}
}
|
if (bean instanceof ConnectionServiceImpl) {
((ConnectionServiceImpl) bean).openConnection();
}
return bean;
| 146
| 34
| 180
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-destructionAwareBeanPostProcessor/src/main/java/com/xcs/spring/service/ConnectionServiceImpl.java
|
ConnectionServiceImpl
|
closeConnection
|
class ConnectionServiceImpl implements ConnectionService {
private boolean isConnected = false;
@Override
public void openConnection() {
isConnected = true;
System.out.println("connection opened.");
}
@Override
public void closeConnection() {<FILL_FUNCTION_BODY>}
@Override
public boolean isConnected() {
return isConnected;
}
}
|
if (isConnected) {
isConnected = false;
System.out.println("connection closed.");
}
| 106
| 34
| 140
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-disposableBean/src/main/java/com/xcs/spring/config/MyDisposableBean.java
|
MyDisposableBean
|
destroy
|
class MyDisposableBean implements DisposableBean {
// 模拟的数据库连接对象
private String databaseConnection;
public MyDisposableBean() {
// 在构造函数中模拟建立数据库连接
this.databaseConnection = "Database connection established";
System.out.println(databaseConnection);
}
@Override
public void destroy() throws Exception {<FILL_FUNCTION_BODY>}
}
|
// 在 destroy 方法中模拟关闭数据库连接
databaseConnection = null;
System.out.println("Database connection closed");
| 114
| 38
| 152
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-initializingBean/src/main/java/com/xcs/spring/config/MyInitializingBean.java
|
MyInitializingBean
|
afterPropertiesSet
|
class MyInitializingBean implements InitializingBean {
private List<String> data;
public List<String> getData() {
return data;
}
@Override
public void afterPropertiesSet() {<FILL_FUNCTION_BODY>}
}
|
// 在此方法中,我们模拟数据加载
data = new ArrayList<>();
data.add("数据1");
data.add("数据2");
data.add("数据3");
System.out.println("MyInitializingBean 初始化完毕,数据已加载!");
| 69
| 77
| 146
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-instantiationAwareBeanPostProcessor/src/main/java/com/xcs/spring/InstantiationAwareBeanPostProcessorApplication.java
|
InstantiationAwareBeanPostProcessorApplication
|
main
|
class InstantiationAwareBeanPostProcessorApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
DataBase userService = context.getBean(DataBase.class);
System.out.println("username = " + userService.getUsername());
System.out.println("password = " + userService.getPassword());
System.out.println("postInstantiationFlag = " + userService.isPostInstantiationFlag());
| 39
| 104
| 143
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-instantiationAwareBeanPostProcessor/src/main/java/com/xcs/spring/config/MyInstantiationAwareBeanPostProcessor.java
|
MyInstantiationAwareBeanPostProcessor
|
postProcessProperties
|
class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (beanClass == DataBase.class) {
System.out.println("正在准备实例化: " + beanName);
}
return null;
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if (bean instanceof DataBase) {
((DataBase) bean).setPostInstantiationFlag(true);
System.out.println("Bean " + beanName + " 已实例化!");
return true;
}
return true;
}
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>}
}
|
if (bean instanceof DataBase) {
MutablePropertyValues mpvs = (MutablePropertyValues) pvs;
mpvs.addPropertyValue("password", "******");
System.out.println(beanName + "的密码已被屏蔽:");
}
return pvs;
| 234
| 77
| 311
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-mergedBeanDefinitionPostProcessor/src/main/java/com/xcs/spring/MergedBeanDefinitionPostProcessorApplication.java
|
MergedBeanDefinitionPostProcessorApplication
|
main
|
class MergedBeanDefinitionPostProcessorApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MyBean bean = context.getBean(MyBean.class);
System.out.println("message = " + bean.getMessage());
| 38
| 56
| 94
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-mergedBeanDefinitionPostProcessor/src/main/java/com/xcs/spring/config/MyMergedBeanDefinitionPostProcessor.java
|
MyMergedBeanDefinitionPostProcessor
|
postProcessAfterInitialization
|
class MyMergedBeanDefinitionPostProcessor implements MergedBeanDefinitionPostProcessor {
/**
* 记录元数据
*/
private Map<String, Map<Field, String>> metadata = new HashMap<>();
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
Field[] fields = beanType.getDeclaredFields();
Map<Field, String> defaultValues = new HashMap<>();
for (Field field : fields) {
if (field.isAnnotationPresent(MyValue.class)) {
MyValue annotation = field.getAnnotation(MyValue.class);
defaultValues.put(field, annotation.value());
}
}
if (!defaultValues.isEmpty()) {
metadata.put(beanName, defaultValues);
}
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>}
}
|
if (metadata.containsKey(beanName)) {
Map<Field, String> defaultValues = metadata.get(beanName);
for (Map.Entry<Field, String> entry : defaultValues.entrySet()) {
Field field = entry.getKey();
String value = entry.getValue();
try {
field.setAccessible(true);
if (field.get(bean) == null) {
field.set(bean, value);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return bean;
| 248
| 149
| 397
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-smartInitializingSingleton/src/main/java/com/xcs/spring/service/MyService.java
|
MyService
|
getDate
|
class MyService {
/**
* 这里使用了Java的Timer来模拟定时任务。在实际应用中,可能会使用更复杂的调度机制。
*/
public void startScheduledTask() {
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
System.out.println(getDate() + " hello world ");
}
},
0,
2000
);
}
/**
* 获取当前时间
*
* @return
*/
public String getDate() {<FILL_FUNCTION_BODY>}
}
|
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return now.format(formatter);
| 170
| 52
| 222
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-interface/spring-interface-smartInstantiationAwareBeanPostProcessor/src/main/java/com/xcs/spring/config/MySmartInstantiationAwareBeanPostProcessor.java
|
MySmartInstantiationAwareBeanPostProcessor
|
determineCandidateConstructors
|
class MySmartInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {
@Override
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {<FILL_FUNCTION_BODY>}
}
|
// 首先,查找@MyAutowired带注释的构造函数
List<Constructor<?>> myAutowiredConstructors = Arrays.stream(beanClass.getConstructors())
.filter(constructor -> constructor.isAnnotationPresent(MyAutowired.class))
.collect(Collectors.toList());
if (!myAutowiredConstructors.isEmpty()) {
return myAutowiredConstructors.toArray(new Constructor<?>[0]);
}
// 其次,检查默认构造函数
try {
Constructor<?> defaultConstructor = beanClass.getDeclaredConstructor();
return new Constructor<?>[]{defaultConstructor};
} catch (NoSuchMethodException e) {
// 找不到默认构造函数,请继续选择合适的构造函数
}
// 返回所有构造函数,让Spring将选择最具体的构造函数
return beanClass.getConstructors();
| 74
| 250
| 324
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-jsr/spring-jsr250-resource/src/main/java/com/xcs/spring/ResourceApplication.java
|
ResourceApplication
|
main
|
class ResourceApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MyController controller = context.getBean(MyController.class);
controller.showService();
| 32
| 47
| 79
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-jsr/spring-jsr330-inject/src/main/java/com/xcs/spring/InjectApplication.java
|
InjectApplication
|
main
|
class InjectApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MyController controller = context.getBean(MyController.class);
controller.showService();
| 33
| 47
| 80
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-jsr/spring-jsr330-named/src/main/java/com/xcs/spring/NamedApplication.java
|
NamedApplication
|
main
|
class NamedApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MyController controller = context.getBean(MyController.class);
controller.showService();
| 33
| 47
| 80
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-jsr/spring-jsr330-provider/src/main/java/com/xcs/spring/ProviderApplication.java
|
ProviderApplication
|
main
|
class ProviderApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MyController controller = context.getBean(MyController.class);
controller.showService();
| 33
| 47
| 80
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-jsr/spring-jsr330-provider/src/main/java/com/xcs/spring/controller/MyController.java
|
MyController
|
showService
|
class MyController {
@Autowired
private Provider<MyService> myServiceProvider;
public void showService(){<FILL_FUNCTION_BODY>}
}
|
System.out.println("myServiceProvider1 = " + myServiceProvider.get());
System.out.println("myServiceProvider2 = " + myServiceProvider.get());
| 47
| 45
| 92
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-jsr/spring-jsr330-qualifier/src/main/java/com/xcs/spring/QualifierApplication.java
|
QualifierApplication
|
main
|
class QualifierApplication {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MessageController messageController = context.getBean(MessageController.class);
messageController.showMessage();
| 33
| 49
| 82
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-metadata/spring-metadata-annotationMetadata/src/main/java/com/xcs/spring/AnnotationMetadataDemoByASM.java
|
AnnotationMetadataDemoByASM
|
main
|
class AnnotationMetadataDemoByASM {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// 创建 MetadataReaderFactory
SimpleMetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory();
// 获取 MetadataReader
MetadataReader metadataReader = readerFactory.getMetadataReader("com.xcs.spring.bean.MyBean");
// 获取 AnnotationMetadata
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
System.out.println("AnnotationMetadata impl class is " + annotationMetadata.getClass());
// 检查 MyBean 类是否被 @Component 注解标记
boolean isComponent = annotationMetadata.hasAnnotation(Component.class.getName());
System.out.println("MyBean is a @Component: " + isComponent);
// 获取 MyBean 类上的注解属性
if (isComponent) {
Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(Component.class.getName());
System.out.println("@Component value is " + annotationAttributes.get("value"));
}
| 40
| 236
| 276
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-metadata/spring-metadata-annotationMetadata/src/main/java/com/xcs/spring/AnnotationMetadataDemoByReflection.java
|
AnnotationMetadataDemoByReflection
|
main
|
class AnnotationMetadataDemoByReflection {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// 获取 AnnotationMetadata
AnnotationMetadata annotationMetadata = AnnotationMetadata.introspect(MyBean.class);
System.out.println("AnnotationMetadata impl class is " + annotationMetadata.getClass());
// 检查 MyBean 类是否被 @Component 注解标记
boolean isComponent = annotationMetadata.hasAnnotation(Component.class.getName());
System.out.println("MyBean is a @Component: " + isComponent);
// 获取 MyBean 类上的注解属性
if (isComponent) {
Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(Component.class.getName());
System.out.println("@Component value is " + annotationAttributes.get("value"));
}
| 40
| 182
| 222
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-metadata/spring-metadata-condition/src/main/java/com/xcs/spring/ConditionDemo.java
|
ConditionDemo
|
main
|
class ConditionDemo {
public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>}
}
|
// 创建资源解析器,用于获取匹配指定模式的资源
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 创建MetadataReader工厂,用于读取类的元数据信息
SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
// 获取指定模式下的所有资源
Resource[] resources = resolver.getResources("classpath*:com/xcs/spring/bean/**/*.class");
// 创建自定义条件类的实例,用于条件匹配
Condition condition = new MyOnClassCondition("com.xcs.spring.ConditionDemo1");
// 遍历每个资源,判断是否满足自定义条件
for (Resource resource : resources) {
// 获取资源对应的元数据读取器
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
// 判断资源是否满足自定义条件
if (condition.matches(null, metadataReader.getAnnotationMetadata())) {
System.out.println(resource.getFile().getName() + "满足条件");
} else {
System.out.println(resource.getFile().getName() + "不满足条件");
}
}
| 35
| 299
| 334
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-metadata/spring-metadata-condition/src/main/java/com/xcs/spring/condition/MyOnClassCondition.java
|
MyOnClassCondition
|
matches
|
class MyOnClassCondition implements Condition {
private final String className;
public MyOnClassCondition(String className) {
this.className = className;
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>}
}
|
try {
// 尝试加载类
getClass().getClassLoader().loadClass(className);
// 类存在,条件匹配
return true;
} catch (ClassNotFoundException e) {
// 类不存在,条件不匹配
return false;
}
| 78
| 75
| 153
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-metadata/spring-metadata-metadataReader/src/main/java/com/xcs/spring/MetadataReaderDemo.java
|
MetadataReaderDemo
|
main
|
class MetadataReaderDemo {
public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>}
}
|
// 创建 MetadataReaderFactory
SimpleMetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory();
// 获取 MetadataReader,通常由 Spring 容器自动创建
MetadataReader metadataReader = readerFactory.getMetadataReader("com.xcs.spring.bean.MyBean");
// 获取类的基本信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
System.out.println("Class Name = " + classMetadata.getClassName());
System.out.println("Class IsInterface = " + classMetadata.isInterface());
System.out.println("Class IsAnnotation = " + classMetadata.isAnnotation());
System.out.println("Class IsAbstract = " + classMetadata.isAbstract());
System.out.println("Class IsConcrete = " + classMetadata.isConcrete());
System.out.println("Class IsFinal = " + classMetadata.isFinal());
System.out.println("Class IsIndependent = " + classMetadata.isIndependent());
System.out.println("Class HasEnclosingClass = " + classMetadata.hasEnclosingClass());
System.out.println("Class EnclosingClassName = " + classMetadata.getEnclosingClassName());
System.out.println("Class HasSuperClass = " + classMetadata.hasSuperClass());
System.out.println("Class SuperClassName = " + classMetadata.getSuperClassName());
System.out.println("Class InterfaceNames = " + Arrays.toString(classMetadata.getInterfaceNames()));
System.out.println("Class MemberClassNames = " + Arrays.toString(classMetadata.getMemberClassNames()));
System.out.println("Class Annotations: " + metadataReader.getAnnotationMetadata().getAnnotationTypes());
System.out.println();
// 获取方法上的注解信息
for (MethodMetadata methodMetadata : metadataReader.getAnnotationMetadata().getAnnotatedMethods("com.xcs.spring.annotation.MyAnnotation")) {
System.out.println("Method Name: " + methodMetadata.getMethodName());
System.out.println("Method DeclaringClassName: " + methodMetadata.getDeclaringClassName());
System.out.println("Method ReturnTypeName: " + methodMetadata.getReturnTypeName());
System.out.println("Method IsAbstract: " + methodMetadata.isAbstract());
System.out.println("Method IsStatic: " + methodMetadata.isStatic());
System.out.println("Method IsFinal: " + methodMetadata.isFinal());
System.out.println("Method IsOverridable: " + methodMetadata.isOverridable());
System.out.println();
}
| 36
| 634
| 670
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-metadata/spring-metadata-typeFilter/src/main/java/com/xcs/spring/TypeFilterDemo.java
|
TypeFilterDemo
|
main
|
class TypeFilterDemo {
public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>}
}
|
// 创建路径匹配的资源模式解析器
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 创建一个简单的元数据读取器工厂
SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
// 创建一个注解类型过滤器,用于匹配带有 MyAnnotation 注解的类
TypeFilter annotationTypeFilter = new AnnotationTypeFilter(MyAnnotation.class);
// 使用资源模式解析器获取所有匹配指定路径的类文件
Resource[] resources = resolver.getResources("classpath*:com/xcs/spring/**/*.class");
// 遍历扫描到的类文件
for (Resource resource : resources) {
// 获取元数据读取器
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
// 使用注解类型过滤器匹配当前类
boolean match = annotationTypeFilter.match(metadataReader, metadataReaderFactory);
// 输出扫描到的文件名和匹配结果
System.out.printf("扫描到的文件: %-20s || 筛选器是否匹配: %s%n", resource.getFile().getName(), match);
}
| 36
| 305
| 341
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-resources/spring-resource-documentLoader/src/main/java/com/xcs/spring/DocumentLoaderDemo.java
|
DocumentLoaderDemo
|
printElementInfo
|
class DocumentLoaderDemo {
public static void main(String[] args) {
try {
// 创建要加载的资源对象
Resource resource = new ClassPathResource("sample.xml");
// 创建 DocumentLoader 实例
DefaultDocumentLoader documentLoader = new DefaultDocumentLoader();
// 加载和解析 XML 文档
Document document = documentLoader.loadDocument(new InputSource(resource.getInputStream()), null, null, 0, true);
// 打印 XML 文档的内容
printDetailedDocumentInfo(document);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 打印详细的XML文档信息,包括元素、属性和文本内容。
*
* @param document 要打印的XML文档对象
*/
private static void printDetailedDocumentInfo(Document document) {
Element rootElement = document.getDocumentElement();
printElementInfo(rootElement, "");
}
/**
* 递归打印XML元素的详细信息,包括元素名称、属性和子节点。
*
* @param element 要打印的XML元素
* @param indent 当前打印的缩进
*/
private static void printElementInfo(Element element, String indent) {<FILL_FUNCTION_BODY>}
}
|
// 打印元素名称
System.out.println(indent + "Element: " + element.getNodeName());
// 打印元素的属性
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
System.out.println(indent + " Attribute: " + attribute.getNodeName() + " = " + attribute.getNodeValue());
}
// 打印元素的子节点(可能是元素或文本)
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
// 如果子节点是元素,递归打印它
printElementInfo((Element) childNode, indent + " ");
} else if (childNode.getNodeType() == Node.TEXT_NODE) {
// 如果子节点是文本,打印文本内容
System.out.println(indent + " Text: " + childNode.getNodeValue().trim());
}
}
| 343
| 315
| 658
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-resources/spring-resource-resourceLoader/src/main/java/com/xcs/spring/DefaultResourceLoaderDemo.java
|
DefaultResourceLoaderDemo
|
main
|
class DefaultResourceLoaderDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
DefaultResourceLoader loader = new DefaultResourceLoader();
// 从类路径加载资源
Resource classpathResource = loader.getResource("classpath:application.properties");
System.out.println("Classpath Exists= " + classpathResource.exists());
// 加载文件系统中的资源
Resource fileResource = loader.getResource("file:/idea-work-space-xcs/spring-reading/spring-resources/spring-resource-resourceLoader/myfile1.txt");
System.out.println("File Exists = " + fileResource.exists());
| 34
| 140
| 174
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-resources/spring-resource-resourceLoader/src/main/java/com/xcs/spring/PathMatchingResourcePatternResolverDemo.java
|
PathMatchingResourcePatternResolverDemo
|
main
|
class PathMatchingResourcePatternResolverDemo {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 加载所有匹配的类路径资源
Resource[] resources = resolver.getResources("classpath*:*.properties");
for (Resource resource : resources) {
System.out.println("Classpath = " + resource.getFilename());
}
// 加载文件系统中的所有匹配资源
Resource[] fileResources = resolver.getResources("file:/idea-work-space-xcs/spring-reading/spring-resources/spring-resource-resourceLoader/*.txt");
for (Resource resource : fileResources) {
System.out.println("File = " + resource.getFilename());
}
| 39
| 176
| 215
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-resources/spring-resource-resourcePatternResolver/src/main/java/com/xcs/spring/ResourcePatternResolverDemo.java
|
ResourcePatternResolverDemo
|
main
|
class ResourcePatternResolverDemo {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 加载所有匹配的类路径资源
Resource[] resources = resolver.getResources("classpath*:*.properties");
for (Resource resource : resources) {
System.out.println("Classpath = " + resource.getFilename());
}
// 加载文件系统中的所有匹配资源
Resource[] fileResources = resolver.getResources("file:/idea-work-space-xcs/spring-reading/spring-resources/spring-resource-resourceLoader/*.txt");
for (Resource resource : fileResources) {
System.out.println("File = " + resource.getFilename());
}
| 36
| 173
| 209
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-resources/spring-resource/src/main/java/com/xcs/spring/ByteArrayResourceDemo.java
|
ByteArrayResourceDemo
|
main
|
class ByteArrayResourceDemo {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
byte[] data = "hello world".getBytes();
Resource resource = new ByteArrayResource(data);
try (InputStream is = resource.getInputStream()) {
// 读取和处理资源内容
System.out.println(new String(is.readAllBytes()));
}
| 36
| 71
| 107
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-resources/spring-resource/src/main/java/com/xcs/spring/ClassPathResourceDemo.java
|
ClassPathResourceDemo
|
main
|
class ClassPathResourceDemo {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
String path = "application.properties";
Resource resource = new ClassPathResource(path);
try (InputStream is = resource.getInputStream()) {
// 读取和处理资源内容
System.out.println(new String(is.readAllBytes()));
}
| 36
| 68
| 104
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-resources/spring-resource/src/main/java/com/xcs/spring/FileSystemResourceDemo.java
|
FileSystemResourceDemo
|
main
|
class FileSystemResourceDemo {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// 请替换你自己的目录
String path = "D:\\idea-work-space-xcs\\spring-reading\\spring-resources\\spring-resource\\myfile.txt";
Resource resource = new FileSystemResource(path);
try (InputStream is = resource.getInputStream()) {
// 读取和处理资源内容
System.out.println(new String(is.readAllBytes()));
}
| 36
| 104
| 140
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-resources/spring-resource/src/main/java/com/xcs/spring/InputStreamResourceDemo.java
|
InputStreamResourceDemo
|
main
|
class InputStreamResourceDemo {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
InputStream isSource = new ByteArrayInputStream("hello world".getBytes());
Resource resource = new InputStreamResource(isSource);
try (InputStream is = resource.getInputStream()) {
// 读取和处理资源内容
System.out.println(new String(is.readAllBytes()));
}
| 36
| 77
| 113
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-resources/spring-resource/src/main/java/com/xcs/spring/UrlResourceDemo.java
|
UrlResourceDemo
|
main
|
class UrlResourceDemo {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Resource resource = new UrlResource("https://dist.apache.org/repos/dist/test/test.txt");
try (InputStream is = resource.getInputStream()) {
// 读取和处理资源内容
System.out.println(new String(is.readAllBytes()));
}
| 36
| 75
| 111
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-beanResolver/src/main/java/com/xcs/spring/BeanResolverDemo.java
|
BeanResolverDemo
|
main
|
class BeanResolverDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建 BeanFactory
// 这里使用注解配置的方式创建 BeanFactory
BeanFactory beanFactory = new AnnotationConfigApplicationContext(MyBean.class).getBeanFactory();
// 创建一个SpEL表达式解析器
ExpressionParser parser = new SpelExpressionParser();
// 创建一个标准的评估上下文
StandardEvaluationContext context = new StandardEvaluationContext();
// 将 BeanFactoryResolver 设置为上下文的 BeanResolver
context.setBeanResolver(new BeanFactoryResolver(beanFactory));
// 解析 SpEL 表达式,获取 Bean 实例
Object myBean = parser.parseExpression("@myBean").getValue(context);
// 打印 Bean 实例
System.out.println("myBean = " + myBean);
| 34
| 203
| 237
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-constructorResolver/src/main/java/com/xcs/spring/ConstructorResolverDemo.java
|
ConstructorResolverDemo
|
main
|
class ConstructorResolverDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个SpEL表达式解析器
ExpressionParser parser = new SpelExpressionParser();
// 解析SpEL表达式,并使用构造函数实例化对象
// 这里的SpEL表达式是一个构造函数调用,创建了一个MyBean对象,参数为'spring-reading'
MyBean myBean = parser.parseExpression("new com.xcs.spring.MyBean('spring-reading')").getValue(MyBean.class);
// 打印输出实例化的MyBean对象
System.out.println(myBean);
| 34
| 144
| 178
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-constructorResolver/src/main/java/com/xcs/spring/MyBean.java
|
MyBean
|
toString
|
class MyBean {
private String name;
public MyBean(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MyBean{" +
"name='" + name + '\'' +
'}';
| 101
| 28
| 129
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-evaluationContext/src/main/java/com/xcs/spring/EvaluationContextDemo.java
|
EvaluationContextDemo
|
main
|
class EvaluationContextDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
// 定义根对象的类
static class MyRootObject {
private String data;
public MyRootObject(String data) {
this.data = data;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
}
|
// 创建评估上下文
EvaluationContext context = new StandardEvaluationContext(new MyRootObject("Root Data"));
// 获取根对象
TypedValue root = context.getRootObject();
System.out.println("根对象: " + root.getValue());
// 设置变量
context.setVariable("name", "John");
System.out.println("变量'name'的值: " + context.lookupVariable("name"));
// 获取属性访问器
List<PropertyAccessor> propertyAccessors = context.getPropertyAccessors();
System.out.println("属性访问器: " + propertyAccessors);
// 获取构造函数解析器
List<ConstructorResolver> constructorResolvers = context.getConstructorResolvers();
System.out.println("构造函数解析器: " + constructorResolvers);
// 获取方法解析器
List<MethodResolver> methodResolvers = context.getMethodResolvers();
System.out.println("方法解析器: " + methodResolvers);
// 获取 bean 解析器
BeanResolver beanResolver = context.getBeanResolver();
System.out.println("bean 解析器: " + beanResolver);
// 获取类型定位器
TypeLocator typeLocator = context.getTypeLocator();
System.out.println("类型定位器: " + typeLocator);
// 获取类型转换器
TypeConverter typeConverter = context.getTypeConverter();
System.out.println("类型转换器: " + typeConverter);
// 获取类型比较器
TypeComparator typeComparator = context.getTypeComparator();
System.out.println("类型比较器: " + typeComparator);
// 获取运算符重载器
OperatorOverloader operatorOverloader = context.getOperatorOverloader();
System.out.println("运算符重载器: " + operatorOverloader);
| 125
| 493
| 618
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-expression/src/main/java/com/xcs/spring/ExpressionDemo.java
|
ExpressionDemo
|
main
|
class ExpressionDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建解析器实例
ExpressionParser parser = new SpelExpressionParser();
// 解析基本表达式
Expression expression = parser.parseExpression("100 + 10");
// 为表达式计算结果
Integer result = expression.getValue(Integer.class);
System.out.println("表达式 '100 + 10' 的结果为: " + result);
| 33
| 102
| 135
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-expressionParser/src/main/java/com/xcs/spring/ExpressionParserDemo.java
|
ExpressionParserDemo
|
main
|
class ExpressionParserDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建解析器实例
ExpressionParser parser = new SpelExpressionParser();
// 解析基本表达式
Expression expression = parser.parseExpression("100 * 2 + 10");
System.out.println("expression = " + expression);
| 38
| 78
| 116
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-methodResolver/src/main/java/com/xcs/spring/MethodResolverDemo.java
|
MethodResolverDemo
|
main
|
class MethodResolverDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个SpEL表达式解析器
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
// 在 MyBean 中定义的方法将被 SpEL 表达式调用
MyBean myBean = new MyBean();
context.setVariable("myBean", myBean);
// 创建一个 SpEL 表达式,调用 MyBean 中的方法
SpelExpression expression = (SpelExpression) parser.parseExpression("#myBean.add(10, 5)");
// 为表达式设置上下文,并计算结果
int result = (int) expression.getValue(context);
// 打印输出实例化的MyBean对象
System.out.println("result = " + result);
| 34
| 196
| 230
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-operatorOverloader/src/main/java/OperatorOverloaderDemo.java
|
OperatorOverloaderDemo
|
main
|
class OperatorOverloaderDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建表达式解析器
ExpressionParser parser = new SpelExpressionParser();
// 创建表达式上下文
StandardEvaluationContext context = new StandardEvaluationContext();
// 创建自定义的OperatorOverloader实例并注册到表达式上下文中
context.setOperatorOverloader(new CustomOperatorOverloader());
context.setVariable("myBean1", new MyBean(18));
context.setVariable("myBean2", new MyBean(20));
// 定义一个SpEL表达式,使用自定义的运算符
Expression expression = parser.parseExpression("#myBean1 + #myBean2");
// 解析并评估表达式
MyBean myBean = expression.getValue(context, MyBean.class);
System.out.println("myBean1+myBean2 = " + myBean);
| 36
| 215
| 251
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-propertyAccessor/src/main/java/com/xcs/spring/PropertyAccessorDemo.java
|
PropertyAccessorDemo
|
main
|
class PropertyAccessorDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个SpEL表达式解析器
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("myBean",new MyBean("spring-reading"));
// 解析SpEL表达式,并使用构造函数实例化对象
String name = parser.parseExpression("#myBean.name").getValue(context, String.class);
System.out.println("name = " + name);
| 35
| 123
| 158
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-typeComparator/src/main/java/com/xcs/spring/TypeComparatorDemo.java
|
TypeComparatorDemo
|
main
|
class TypeComparatorDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个EvaluationContext
StandardEvaluationContext context = new StandardEvaluationContext();
// 创建SpEL表达式解析器
SpelExpressionParser parser = new SpelExpressionParser();
// 解析表达式
Expression expression = parser.parseExpression("'2' < '-5.0'");
// 使用TypeComparator进行比较
boolean result = expression.getValue(context,Boolean.class);
// 打印比较后的值
System.out.println("result : " + result);
| 35
| 134
| 169
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-typeConverter/src/main/java/com/xcs/spring/TypeConverterDemo.java
|
TypeConverterDemo
|
main
|
class TypeConverterDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建SpEL表达式解析器
SpelExpressionParser parser = new SpelExpressionParser();
// 创建一个EvaluationContext
StandardEvaluationContext context = new StandardEvaluationContext();
// 定义一个需要转换的值
String stringValue = "'123'";
// 解析表达式
Expression expression = parser.parseExpression(stringValue);
// 使用TypeConverter进行转换
Integer intValue = expression.getValue(context, Integer.class);
// 打印转换后的值
System.out.println("Converted Integer value: " + intValue);
| 34
| 157
| 191
|
<no_super_class>
|
xuchengsheng_spring-reading
|
spring-reading/spring-spel/spring-spel-typeLocator/src/main/java/com/xcs/spring/TypeLocatorDemo.java
|
TypeLocatorDemo
|
main
|
class TypeLocatorDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// 创建一个SpEL表达式解析器
ExpressionParser parser = new SpelExpressionParser();
// 解析表达式获取 Date 类的 Class 对象
Class dateClass = parser.parseExpression("T(java.util.Date)").getValue(Class.class);
System.out.println("dateClass = " + dateClass);
// 解析表达式获取 String 类的 Class 对象
Class stringClass = parser.parseExpression("T(String)").getValue(Class.class);
System.out.println("stringClass = " + stringClass);
// 解析表达式比较两个 RoundingMode 枚举值的大小
boolean trueValue = parser.parseExpression("T(java.math.RoundingMode).CEILING < T(java.math.RoundingMode).FLOOR").getValue(Boolean.class);
System.out.println("trueValue = " + trueValue);
| 34
| 223
| 257
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/classify/BinaryExceptionClassifier.java
|
BinaryExceptionClassifier
|
classify
|
class BinaryExceptionClassifier extends SubclassClassifier<Throwable, Boolean> {
private boolean traverseCauses;
public static BinaryExceptionClassifierBuilder builder() {
return new BinaryExceptionClassifierBuilder();
}
public static BinaryExceptionClassifier defaultClassifier() {
// create new instance for each call due to mutability
return new BinaryExceptionClassifier(
Collections.<Class<? extends Throwable>, Boolean>singletonMap(Exception.class, true), false);
}
/**
* Create a binary exception classifier with the provided default value.
* @param defaultValue defaults to false
*/
public BinaryExceptionClassifier(boolean defaultValue) {
super(defaultValue);
}
/**
* Create a binary exception classifier with the provided classes and their
* subclasses. The mapped value for these exceptions will be the one provided (which
* will be the opposite of the default).
* @param exceptionClasses the exceptions to classify among
* @param value the value to classify
*/
public BinaryExceptionClassifier(Collection<Class<? extends Throwable>> exceptionClasses, boolean value) {
this(!value);
if (exceptionClasses != null) {
Map<Class<? extends Throwable>, Boolean> map = new HashMap<>();
for (Class<? extends Throwable> type : exceptionClasses) {
map.put(type, !getDefault());
}
setTypeMap(map);
}
}
/**
* Create a binary exception classifier with the default value false and value mapping
* true for the provided classes and their subclasses.
* @param exceptionClasses the exception types to throw
*/
public BinaryExceptionClassifier(Collection<Class<? extends Throwable>> exceptionClasses) {
this(exceptionClasses, true);
}
/**
* Create a binary exception classifier using the given classification map and a
* default classification of false.
* @param typeMap the map of types
*/
public BinaryExceptionClassifier(Map<Class<? extends Throwable>, Boolean> typeMap) {
this(typeMap, false);
}
/**
* Create a binary exception classifier using the given classification map and the
* given value for default class.
* @param defaultValue the default value to use
* @param typeMap the map of types to classify
*/
public BinaryExceptionClassifier(Map<Class<? extends Throwable>, Boolean> typeMap, boolean defaultValue) {
super(typeMap, defaultValue);
}
/**
* Create a binary exception classifier.
* @param defaultValue the default value to use
* @param typeMap the map of types to classify
* @param traverseCauses if true, throwable's causes will be inspected to find
* non-default class
*/
public BinaryExceptionClassifier(Map<Class<? extends Throwable>, Boolean> typeMap, boolean defaultValue,
boolean traverseCauses) {
super(typeMap, defaultValue);
this.traverseCauses = traverseCauses;
}
public void setTraverseCauses(boolean traverseCauses) {
this.traverseCauses = traverseCauses;
}
@Override
public Boolean classify(Throwable classifiable) {<FILL_FUNCTION_BODY>}
}
|
Boolean classified = super.classify(classifiable);
if (!this.traverseCauses) {
return classified;
}
/*
* If the result is the default, we need to find out if it was by default or so
* configured; if default, try the cause(es).
*/
if (classified.equals(this.getDefault())) {
Throwable cause = classifiable;
do {
if (this.getClassified().containsKey(cause.getClass())) {
return classified; // non-default classification
}
cause = cause.getCause();
classified = super.classify(cause);
}
while (cause != null && classified.equals(this.getDefault()));
}
return classified;
| 822
| 197
| 1,019
|
<methods>public void <init>() ,public void <init>(java.lang.Boolean) ,public void <init>(Map<Class<? extends java.lang.Throwable>,java.lang.Boolean>, java.lang.Boolean) ,public void add(Class<? extends java.lang.Throwable>, java.lang.Boolean) ,public java.lang.Boolean classify(java.lang.Throwable) ,public final java.lang.Boolean getDefault() ,public void setDefaultValue(java.lang.Boolean) ,public void setTypeMap(Map<Class<? extends java.lang.Throwable>,java.lang.Boolean>) <variables>private ConcurrentMap<Class<? extends java.lang.Throwable>,java.lang.Boolean> classified,private java.lang.Boolean defaultValue
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/classify/BinaryExceptionClassifierBuilder.java
|
BinaryExceptionClassifierBuilder
|
build
|
class BinaryExceptionClassifierBuilder {
/**
* Building notation type (white list or black list) - null: has not selected yet -
* true: white list - false: black list
*/
private Boolean isWhiteList = null;
private boolean traverseCauses = false;
private final List<Class<? extends Throwable>> exceptionClasses = new ArrayList<>();
public BinaryExceptionClassifierBuilder retryOn(Class<? extends Throwable> throwable) {
Assert.isTrue(isWhiteList == null || isWhiteList, "Please use only retryOn() or only notRetryOn()");
Assert.notNull(throwable, "Exception class can not be null");
isWhiteList = true;
exceptionClasses.add(throwable);
return this;
}
public BinaryExceptionClassifierBuilder notRetryOn(Class<? extends Throwable> throwable) {
Assert.isTrue(isWhiteList == null || !isWhiteList, "Please use only retryOn() or only notRetryOn()");
Assert.notNull(throwable, "Exception class can not be null");
isWhiteList = false;
exceptionClasses.add(throwable);
return this;
}
public BinaryExceptionClassifierBuilder traversingCauses() {
this.traverseCauses = true;
return this;
}
public BinaryExceptionClassifier build() {<FILL_FUNCTION_BODY>}
}
|
Assert.isTrue(!exceptionClasses.isEmpty(),
"Attempt to build classifier with empty rules. To build always true, or always false "
+ "instance, please use explicit rule for Throwable");
BinaryExceptionClassifier classifier = new BinaryExceptionClassifier(exceptionClasses, isWhiteList // using
// white
// list
// means
// classifying
// provided
// classes
// as
// "true"
// (is
// retryable)
);
classifier.setTraverseCauses(traverseCauses);
return classifier;
| 362
| 182
| 544
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/classify/ClassifierAdapter.java
|
ClassifierAdapter
|
setDelegate
|
class ClassifierAdapter<C, T> implements Classifier<C, T> {
private MethodInvoker invoker;
private Classifier<C, T> classifier;
/**
* Default constructor for use with setter injection.
*/
public ClassifierAdapter() {
super();
}
/**
* Create a new {@link Classifier} from the delegate provided. Use the constructor as
* an alternative to the {@link #setDelegate(Object)} method.
* @param delegate the delegate
*/
public ClassifierAdapter(Object delegate) {
setDelegate(delegate);
}
/**
* Create a new {@link Classifier} from the delegate provided. Use the constructor as
* an alternative to the {@link #setDelegate(Classifier)} method.
* @param delegate the classifier to delegate to
*/
public ClassifierAdapter(Classifier<C, T> delegate) {
this.classifier = delegate;
}
public void setDelegate(Classifier<C, T> delegate) {
this.classifier = delegate;
this.invoker = null;
}
/**
* Search for the {@link org.springframework.classify.annotation.Classifier
* Classifier} annotation on a method in the supplied delegate and use that to create
* a {@link Classifier} from the parameter type to the return type. If the annotation
* is not found a unique non-void method with a single parameter will be used, if it
* exists. The signature of the method cannot be checked here, so might be a runtime
* exception when the method is invoked if the signature doesn't match the classifier
* types.
* @param delegate an object with an annotated method
*/
public final void setDelegate(Object delegate) {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public T classify(C classifiable) {
if (this.classifier != null) {
return this.classifier.classify(classifiable);
}
return (T) this.invoker.invokeMethod(classifiable);
}
}
|
this.classifier = null;
this.invoker = MethodInvokerUtils
.getMethodInvokerByAnnotation(org.springframework.classify.annotation.Classifier.class, delegate);
if (this.invoker == null) {
this.invoker = MethodInvokerUtils.<C, T>getMethodInvokerForSingleArgument(delegate);
}
Assert.state(this.invoker != null, "No single argument public method with or without "
+ "@Classifier was found in delegate of type " + delegate.getClass());
| 524
| 138
| 662
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/classify/PatternMatcher.java
|
PatternMatcher
|
match
|
class PatternMatcher<S> {
private Map<String, S> map = new HashMap<>();
private List<String> sorted = new ArrayList<>();
/**
* Initialize a new {@link PatternMatcher} with a map of patterns to values
* @param map a map from String patterns to values
*/
public PatternMatcher(Map<String, S> map) {
super();
this.map = map;
// Sort keys to start with the most specific
this.sorted = new ArrayList<>(map.keySet());
this.sorted.sort((o1, o2) -> {
String s1 = o1; // .replace('?', '{');
String s2 = o2; // .replace('*', '}');
return s2.compareTo(s1);
});
}
/**
* Lifted from AntPathMatcher in Spring Core. Tests whether or not a string matches
* against a pattern. The pattern may contain two special characters:<br>
* '*' means zero or more characters<br>
* '?' means one and only one character
* @param pattern pattern to match against. Must not be <code>null</code>.
* @param str string which must be matched against the pattern. Must not be
* <code>null</code>.
* @return <code>true</code> if the string matches against the pattern, or
* <code>false</code> otherwise.
*/
public static boolean match(String pattern, String str) {<FILL_FUNCTION_BODY>}
/**
* <p>
* This method takes a String key and a map from Strings to values of any type. During
* processing, the method will identify the most specific key in the map that matches
* the line. Once the correct is identified, its value is returned. Note that if the
* map contains the wildcard string "*" as a key, then it will serve as the "default"
* case, matching every line that does not match anything else.
*
* <p>
* If no matching prefix is found, a {@link IllegalStateException} will be thrown.
*
* <p>
* Null keys are not allowed in the map.
* @param line An input string
* @return the value whose prefix matches the given line
*/
public S match(String line) {
S value = null;
Assert.notNull(line, "A non-null key must be provided to match against.");
for (String key : this.sorted) {
if (PatternMatcher.match(key, line)) {
value = this.map.get(key);
break;
}
}
if (value == null) {
throw new IllegalStateException("Could not find a matching pattern for key=[" + line + "]");
}
return value;
}
}
|
char[] patArr = pattern.toCharArray();
char[] strArr = str.toCharArray();
int patIdxStart = 0;
int patIdxEnd = patArr.length - 1;
int strIdxStart = 0;
int strIdxEnd = strArr.length - 1;
char ch;
boolean containsStar = pattern.contains("*");
if (!containsStar) {
// No '*'s, so we make a shortcut
if (patIdxEnd != strIdxEnd) {
return false; // Pattern and string do not have the same size
}
for (int i = 0; i <= patIdxEnd; i++) {
ch = patArr[i];
if (ch != '?') {
if (ch != strArr[i]) {
return false;// Character mismatch
}
}
}
return true; // String matches against pattern
}
if (patIdxEnd == 0) {
return true; // Pattern contains only '*', which matches anything
}
// Process characters before first star
while ((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) {
if (ch != '?') {
if (ch != strArr[strIdxStart]) {
return false;// Character mismatch
}
}
patIdxStart++;
strIdxStart++;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
// Process characters after last star
while ((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) {
if (ch != '?') {
if (ch != strArr[strIdxEnd]) {
return false;// Character mismatch
}
}
patIdxEnd--;
strIdxEnd--;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
// process pattern between stars. padIdxStart and patIdxEnd point
// always to a '*'.
while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {
int patIdxTmp = -1;
for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {
if (patArr[i] == '*') {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == patIdxStart + 1) {
// Two stars next to each other, skip the first one.
patIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp - patIdxStart - 1);
int strLength = (strIdxEnd - strIdxStart + 1);
int foundIdx = -1;
strLoop: for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
ch = patArr[patIdxStart + j + 1];
if (ch != '?') {
if (ch != strArr[strIdxStart + i + j]) {
continue strLoop;
}
}
}
foundIdx = strIdxStart + i;
break;
}
if (foundIdx == -1) {
return false;
}
patIdxStart = patIdxTmp;
strIdxStart = foundIdx + patLength;
}
// All characters in the string are used. Check if only '*'s are left
// in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
| 718
| 1,252
| 1,970
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.