?
其实就是用aware来加载外部文件,增加spring容器与bean的耦合度 javaboy.properties
javaboy.address=www.whereami.org
javaboy.txt
AwareService.java
package org.javaboy.aware;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.core.io.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author 邓雪松 (づ ̄ 3 ̄)づ)
* @create 2021-10-25-21-36
* 利用aware加载外部资源
* BeanNameAware:获得Bean的名称,BeanFactoryAware:获取当前的beanfactory,ResourceLoaderAware:获取资源加载器,EnvironmentAwareree:获取环境信息
*/
@Service
@PropertySource(value="javaboy.properties")
public class AwareService implements BeanNameAware,BeanFactoryAware,ResourceLoaderAware,EnvironmentAware {
private String beanName;
private ResourceLoader resourceLoader;
private Environment environment;
public void output() throws IOException {
System.out.println("beanName = "+beanName);
Resource resource = resourceLoader.getResource("javaboy.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
String s = br.readLine();
System.out.println("s = "+s);
br.close();
String address = environment.getProperty("javaboy.address");
System.out.println("address = "+address);
}
//获取bean的生成工厂
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
}
//获取Bean的名字
public void setBeanName(String name) {
this.beanName = name;
}
public void setEnvironment(Environment environment) {
this.environment = environment;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
}
JavaConfig.java
package org.javaboy.aware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @author 邓雪松 (づ ̄ 3 ̄)づ)
* @create 2021-10-25-22-01
*/
@Configuration
@ComponentScan
public class JavaConfig {
}
Main.java
package org.javaboy.aware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.io.IOException;
/**
* @author 邓雪松 (づ ̄ 3 ̄)づ)
* @create 2021-10-25-22-01
*/
public class Main {
public static void main(String[] args) throws IOException {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(JavaConfig.class);
AwareService bean = ctx.getBean(AwareService.class);
bean.output();
}
}
?
|