新增spring-annotation-lazy

master
xuchengsheng 2023-10-10 22:57:55 +08:00
parent 81ab090bbe
commit 3794c0e872
6 changed files with 92 additions and 0 deletions

View File

@ -19,6 +19,7 @@
<module>spring-annotation-propertySource</module>
<module>spring-annotation-componentScan</module>
<module>spring-annotation-dependsOn</module>
<module>spring-annotation-lazy</module>
</modules>
</project>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-annotation</artifactId>
<groupId>com.xcs.spring</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-annotation-lazy</artifactId>
</project>

View File

@ -0,0 +1,25 @@
package com.xcs.spring;
import com.xcs.spring.config.MyConfiguration;
import com.xcs.spring.service.MyService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author xcs
* @date 20230807 1621
**/
public class LazyApplication {
public static void main(String[] args) {
System.out.println("启动 Spring ApplicationContext...");
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
System.out.println("完成启动 Spring ApplicationContext...");
System.out.println("准备获取MyService...");
MyService myService = context.getBean(MyService.class);
System.out.println("成功获取MyService...-->" + myService);
System.out.println("调用show方法...");
myService.show();
}
}

View File

@ -0,0 +1,12 @@
package com.xcs.spring.bean;
public class MyBean {
public MyBean() {
System.out.println("MyBean 的构造函数被调用了!");
}
public void show() {
System.out.println("hello world");
}
}

View File

@ -0,0 +1,23 @@
package com.xcs.spring.config;
import com.xcs.spring.bean.MyBean;
import com.xcs.spring.service.MyService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Configuration
public class MyConfiguration {
@Bean
@Lazy
public MyBean myBean(){
System.out.println("MyBean 初始化了!");
return new MyBean();
}
@Bean
public MyService myService(){
return new MyService();
}
}

View File

@ -0,0 +1,17 @@
package com.xcs.spring.service;
import com.xcs.spring.bean.MyBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
public class MyService {
@Autowired
@Lazy
private MyBean myBean;
public void show() {
System.out.println("@Lazy MyBean = " + myBean.getClass());
myBean.show();
}
}