Bean的Scope -demo.springboot.scope
- Singleton:一個Spring容器只有一個,默認選項
- Prototype:每次調用創建一個新的Bean
- Requst:給每個requst創建一個新的Bean
- Session:給每個session創建一個新的Bean
@Service
@Scope("prototype")
public class DemoPrototypeService {
}
SpringEL -demo.springboot.el
@PropertySource:在Java中引入properties/xml文件
@Value:注入值到對應的屬性中,來源可以是文件/url/靜態方法等,通過表達式訪問
@PropertySource("classpath:el/test.properties")
public class ElConfig {
@Value("Love U")
String normal;
@Value("#{systemProperties['os.name']}")
String osName;
@Value("#{T(java.lang.Math).random()*100.00}")
double randomNumber;
@Value("#{demoReadFileService.addition}")
String addition;
@Value("classpath:el/test.txt")
Resource testFile;
@Value("http://www.baidu.com")
Resource testUrl;
@Value("${project.name}")
String projectName;
}
Bean的工作流程 -demo.springboot.prepost
構造函數-》init方法-》destroy方法
* 可以通過@Bean(initMethod=” “,destroyMethod=” “)指定Bean的生存週期方法
* 可以通過@PostConstruct@PreDestroy,在Bean內部預先註解好生存週期方法
//Bean方式
public class BeanWayService {
public BeanWayService() {}
public void init() {}
public void destroy() {}
}
//JSR方式
public class JSR250WayService {
public JSR250WayService() {}
@PostConstruct
public void init() {}
@PreDestroy
public void destroy() {}
}
//實際使用
public class ProPostConfig {
@Bean(initMethod = "init", destroyMethod = "destroy")
BeanWayService beanWayService() { return new BeanWayService(); }
@Bean
JSR250WayService jsr250WayService() { return new JSR250WayService(); }
}
Profile 不同環境的配置切換
在JVM或者application.yaml裏設置 spring.profiles.active=xxx ,spring裏會根據Profile名稱匹配
* 使用@Profile(…)註解需要切換的@Bean,
* 設置application-dev.yaml/application-test.yaml等不同配置
public class ProfileConfig {
@Bean
@Profile("dev")
public String devBean() { return "獲取dev"; }
@Bean
@Profile("test")
public String testBean() { return "獲取test"; }
}
事件
Bean與Bean的消息通信:定義事件-》定義監聽-》發佈事件
* 自定義事件,繼承ApplicationEvent(還有一些內置的Event)
public class DemoEvent extends ApplicationEvent {
private String msg;
public DemoEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
public String getMsg() { return msg; }
public void setMsg(String msg) { this.msg = msg; }
}
- 定義監聽器,實現ApplicationListener,指定監聽的事件類
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
@Override
public void onApplicationEvent(DemoEvent event) {
String msg = event.getMsg();
System.out.println("收到了DemoEvent的消息:" + msg);
}
}
- 發送事件,通過獲取AbstractApplicationContext,執行publishEvent函數發佈事件
@Component
public class DemoPublisher {
@Autowired
AbstractApplicationContext context;
public void pulish() {
context.publishEvent(new DemoEvent(this, "歡迎歡迎"));
}
}
- 測試
@Configuration
@ComponentScan("demo.springboot.event")
public class EventConfig {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
DemoPublisher publisher = context.getBean(DemoPublisher.class);
publisher.pulish();
context.close();
}
}