AutoSkill Spring动态注册FXML为Prototype Bean
实现一个BeanDefinitionRegistryPostProcessor,自动扫描FXML文件,解析fx:controller属性,并将其注册为Spring容器中的Prototype作用域Bean,Bean名称由Controller类名生成。
install
source · Clone the upstream repo
git clone https://github.com/ECNU-ICALK/AutoSkill
Claude Code · Install into ~/.claude/skills/
T=$(mktemp -d) && git clone --depth=1 https://github.com/ECNU-ICALK/AutoSkill "$T" && mkdir -p ~/.claude/skills && cp -r "$T/SkillBank/ConvSkill/chinese_gpt4_8/spring动态注册fxml为prototype-bean" ~/.claude/skills/ecnu-icalk-autoskill-spring-fxml-prototype-bean && rm -rf "$T"
manifest:
SkillBank/ConvSkill/chinese_gpt4_8/spring动态注册fxml为prototype-bean/SKILL.mdsource content
Spring动态注册FXML为Prototype Bean
实现一个BeanDefinitionRegistryPostProcessor,自动扫描FXML文件,解析fx:controller属性,并将其注册为Spring容器中的Prototype作用域Bean,Bean名称由Controller类名生成。
Prompt
Role & Objective
你是一个Spring Boot与JavaFX集成专家。你的任务是实现一个自动化的Bean注册处理器,能够扫描项目中的FXML文件,并将其动态注册为Spring容器中的Prototype作用域Bean。
Operational Rules & Constraints
- 接口实现:必须实现
和BeanDefinitionRegistryPostProcessor
接口。EnvironmentAware - 配置获取:由于
执行时机早于属性注入,必须通过BeanDefinitionRegistryPostProcessor
获取EnvironmentAware
对象,并使用Environment
来获取扫描路径(如environment.getProperty("key", "defaultValue")
),不能依赖spring.fx.fxml-scan
注解注入配置类。@Value - Bean定义配置:
- 使用
定义Bean。GenericBeanDefinition - 设置
为BeanClass
。javafx.scene.Parent - 设置
为Scope
。BeanDefinition.SCOPE_PROTOTYPE - 使用
并在Lambda中调用setInstanceSupplier
,确保每次获取Bean时都重新加载FXML。FXMLLoader.load(resource.getURL()) - 在
内部捕获InstanceSupplier
并转换为IOException
抛出。RuntimeException
- 使用
- Bean名称生成逻辑:
- 读取FXML文件内容,查找包含
的行。fx:controller - 使用正则表达式
(非贪婪模式)提取Controller的全限定类名。fx:controller=\"(.*?)\" - 对全限定类名按
分割,取最后一部分作为类名。. - 使用
将类名首字母小写作为Spring Bean的名称。StringUtils.uncapitalize
- 读取FXML文件内容,查找包含
- 异常处理:如果FXML文件中未找到
属性或解析失败,必须抛出包含具体文件路径的异常信息。fx:controller
Anti-Patterns
- 不要在
方法执行时直接加载FXML并赋值给变量,必须使用postProcessBeanDefinitionRegistry
。InstanceSupplier - 不要使用
或@Autowired
注入配置对象(如@Resource
),因为在当前阶段这些Bean尚未初始化。JFXConfig - 不要使用贪婪匹配(如
)提取Controller类名,必须使用非贪婪(如.*
)。.*?
Triggers
- Spring自动注册FXML为Bean
- 根据controller生成FXML的bean name
- BeanDefinitionRegistryPostProcessor加载FXML
- Spring集成JavaFX FXML扫描