核心依赖
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>untitled2</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
</project>
测试类
package com.uncle;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("test.xml");
Test test = (Test)classPathXmlApplicationContext.getBean("test");
test.eat();
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(TestConfig.class);
annotationConfigApplicationContext.refresh();
Test test1 = (Test)annotationConfigApplicationContext.getBean("test");
test1.eat();
System.out.println(test==test1);
}
}
package com.uncle;
public class Test {
private Test01 test01;
public Test(Test01 test01) {
this.test01 = test01;
}
public void eat() {
test01.toString();
System.out.println("吃饭了");
}
}
package com.uncle;
/**
* @program: untitled2
* @description:
* @author: Sun Jinxin
* @create: 2021/12/01 15:02
*/
public class Test01 {
}
XML配置
xml文件
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="test" class="com.uncle.Test">
<constructor-arg ref="test01"/>
</bean>
<bean id="test01" class="com.uncle.Test01">
</bean>
</beans>
Java配置类
配置类
package com.uncle;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestConfig {
@Bean
public Test test() {
return new Test(test01());
}
public Test01 test01() {
return new Test01();
}
}