测试环境使用的是 springboot 项目 , 没有 web 依赖
pom.xml
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.4.RELEASEversion>
<relativePath/>
parent>
<groupId>com.examplegroupId>
<artifactId>springboot-demoartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>springboot-demoname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-autoconfigureartifactId>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
项目示例

package com.example.xmlcontext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringXmlContextTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
BBean bBean1 = ac.getBean(BBean.class);
System.out.println(bBean1);
BBean bBean2 = (BBean) ac.getBean("bBean");
System.out.println(bBean2);
System.out.println("获取的两个对象是否相等 : "+ (bBean1==bBean2));
}
}
package com.example.gemerxml;
import org.springframework.context.support.GenericXmlApplicationContext;
public class SpringGenericXmlTest {
public static void main(String[] args) {
GenericXmlApplicationContext ac = new GenericXmlApplicationContext("classpath:applicationContextGen.xml");
DBean bean = ac.getBean(DBean.class);
System.out.println(bean);
}
}
基于 this 进行扫描
package com.example.annotationcontext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.example.annotationcontext")
public class SpringAnnotationcontextTest1 {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringAnnotationcontextTest1.class);
A bean = ac.getBean(A.class);
System.out.println(bean);
}
}
基于扫描包进行扫描
package com.example.annotationscanner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringAnnotationScanner {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext("com.example.annotationscanner");
CBean bean = ac.getBean(CBean.class);
System.out.println(bean);
}
}