springboot监听文件笔记

本文介绍了如何在SpringBoot项目中监听外部配置文件,包括创建监听器类、配置监视器以及启动类的设置,旨在实现根据文件内容动态调整项目参数。同时,文章讨论了如何动态获取配置文件的绝对路径,避免硬编码。

最近公司项目需要对外部配置文件进行监听,根据文件内容进行相应的修改。所以就学习了下

一、监听器类

@Component
public class FileListener extends FileAlterationListenerAdaptor {
	
	private Logger log = LoggerFactory.getLogger(FileListener.class);
	 // 声明业务服务
	@Autowired
	Service sevice;
	
    // 文件创建执行
    @Override
    public void onFileCreate(File file) {
        log.info("[新建]:" + file.getAbsolutePath());
        
        System.out.println("文件创建了。。。。。");
    }
 
    // 文件创建修改
    @Override
    public void onFileChange(File file) {
        log.info("[修改]:" + file.getAbsolutePath());

    }
 
    // 文件创建删除
    @Override
    public void onFileDelete(File file) {
        log.info("[删除]:" + file.getAbsolutePath());
        System.out.println("文件被删除");
    }
 
    // 目录创建
    @Override
    public void onDirectoryCreate(File directory) {
        log.info("[目录创建]:" + directory.getAbsolutePath());
    }
 
    // 目录修改
    @Override
    public void onDirectoryChange(File directory) {
        log.info("[目录修改]:" + directory.getAbsolutePath());
    }
 
    // 目录删除
    @Override
    public void onDirectoryDelete(File directory) {
        log.info("[目录删除]:" + directory.getAbsolutePath());
    }
}

注意这个监听器类最小监听单位是文件夹,不能定向监听文件。

二、配置监视器

springboot配置中注入监视器bean

	@Bean
	public FileAlterationMonitor monitor(FileListener listener) {
		FileAlterationMonitor monitor = new FileAlterationMonitor(1000l);
		//参数传值是多久检查一次文件,单位毫秒
		String string = this.getClass().getClassLoader().getResource("xxx").toString();
    	String path = string.substring(string.indexOf("/")+1, string.length());  
		FileAlterationObserver observer = new FileAlterationObserver(new File(path));//创建观察者
		observer.addListener(listener);
        monitor.addObserver(observer);
        
        return monitor;
	}

三、启动类配置

ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
		FileAlterationMonitor monitor = context.getBean(FileAlterationMonitor.class);
		try {
			monitor.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("监听器启动失败");
		}

四、关于如何读取外部配置文件

一般来说,某个项目希望通过配置文件改变某些参数来调整,但是这些文件又不能打进jar包,就必须采用读取外部配置文件的方式进行。
这时候就必须要获得绝对路径。

		Properties prop = new Properties();
		InputStream input =  new FileInputStream(new File("D:/my.properties"));
		prop.load(input);
		String property = prop.getProperty("aaa");
		System.out.println(property);

上面这个把路径写死了,我们希望能根据jar包位置来获取路径

		Properties prop = new Properties();
		String resource = this.getClass().getClassLoader().getResource("").toString();
		String substring = resource.substring(0, resource.indexOf("项目名")).concat("具体文件名");
		 String s = substring.substring(resource.indexOf("/")+1);
		System.out.println(s);
		FileInputStream input  = new FileInputStream(new  File(s));
		prop.load(input);

这里举了个例子,是读取项目同文件夹下的配置文件。

### Spring Boot 和 Vue 技术学习资料汇总 #### 一、Spring Boot 配置与集成 MyBatis 在构建基于 Spring Boot 的后端服务时,可以通过 `@MapperScan` 注解实现对 Mapper 文件夹的扫描功能。例如,在启动类中添加如下代码即可完成配置[^1]: ```java @SpringBootApplication @MapperScan("com.example.test.mapper") public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } } ``` 对于前后端分离的应用场景,建议避免在初始阶段引入复杂的数据库依赖(如 MyBatis),以免因未正确配置而导致项目无法正常启动[^2]。 --- #### 二、Swagger 文档工具支持 为了提升 API 开发效率并便于调试接口,可以引入 Swagger 工具库作为文档生成器。以下是 Maven 中的相关依赖配置示例[^3]: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> ``` 通过此方式,开发者能够直观查看 RESTful 接口定义及其调用方法。 --- #### 三、Vue.js 环境搭建指南 针对前端部分,推荐采用官方脚手架工具 vue-cli 构建工程框架。初始化过程中涉及多项选项设定,包括但不限于 TypeScript 支持、路由管理以及状态管理模式的选择等[^5]: | **字段描述** | **可选值说明** | |--------------|----------------| | 使用模板 | 手工创建 (Manually select features) 或预设方案 | | 功能模块 | TS / Router / Vuex | | 版本号 | Vue 3.x | | Class Component | 是否启用 Java 类风格组件 | | Babel 插件 | 结合 TypeScript 转译 | | History Mode | 地址栏 URL 形式 | 安装完成后可通过命令行执行以下指令验证环境是否可用: ```bash npm run serve ``` --- #### 四、前后端联调实践技巧 当分别完成了各自平台的基础建设之后,则需要考虑如何将两者结合起来形成完整的解决方案。一种常见做法是把编译后的静态资源复制至服务器根目录下的特定位置(如 `/resources/static/`)。与此同时调整应用属性文件内的监听端口号参数以匹配实际需求[^2]: ```properties server.port=8443 ``` 最后重启整个应用程序确认一切运转顺畅无误为止。 --- ### 示例代码片段展示 下面给出一段简单演示登录逻辑处理流程的例子供参考之用: ```java @RestController @RequestMapping("/api/auth") public class LoginController { private final UserService userService; public LoginController(UserService userService){ this.userService = userService; } @PostMapping("/login") public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest){ Authentication authentication = null; try{ authentication = authService.authenticate(loginRequest.getUsername(), loginRequest.getPassword()); }catch(AuthenticationException e){ return new ResponseEntity<>(new ApiResponse(false,"Invalid username/password supplied"), HttpStatus.UNAUTHORIZED); } SecurityContextHolder.getContext().setAuthentication(authentication); String jwtToken = tokenProvider.generateToken(authentication); return ResponseEntity.ok(new JwtResponse(jwtToken)); } } ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值