# 项目代码资源:
可能还在审核中,请等待。。。
https://download.csdn.net/download/chenhz2284/89434148
# 项目代码
【pom.xml】
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.3.12.RELEASE</version>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId><version>2.3.12.RELEASE</version>
</dependency>
<dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.11</version>
</dependency>
【application.properties】
server.port=8080
spring.application.name=myBeanMainmanagement.server.port=7001
management.endpoints.web.exposure.include=*
【my_beans.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="mainBean2" class="com.chz.myBeanMain.bean.MainBean2"></bean></beans>
注意xml里面定义了一个【mainBean2】
【MainBean1.java】
package com.chz.myBeanMain.bean;@Slf4j
@Getter
@Setter
@Component
public class MainBean1 {public MainBean1(){log.info("chz >>> MainBean1.<init>()");}private String name = "MainBean1";}
【MainBean2.java】
package com.chz.myBeanMain.bean;@Slf4j
@Getter
@Setter
//@Component // 注意MainBean2是没有【@Component】注解的
public class MainBean2 {public MainBean2(){log.info("chz >>> MainBean1.<init>()");}private String name = "MainBean2";}
【MainController.java】
package com.chz.myBeanMain.controller;@Slf4j
@RestController
@RequestMapping("/main")
public class MainController {@Autowired(required = false)private MainBean1 mainBean1;@Autowired(required = false)private MainBean2 mainBean2; // 这里注入【MainBean2】@GetMapping("/mainBean1")public String mainBean1() {return "mainBean1: " + mainBean1.getName();}@GetMapping("/mainBean2")public String mainBean2() {return "mainBean2: " + mainBean2.getName();}
}
【MyBeanMainTest.java】
package com.chz.myBeanMain;@ImportResource(locations = {"classpath:my_beans.xml"}) // 这里导入【MainBean2】的xml
@SpringBootApplication
public class MyBeanMainTest {public static void main(String[] args) {SpringApplication.run(MyBeanMainTest.class, args);}
}
运行【MyBeanMainTest】
访问【http://localhost:8080/main/mainBean2】
MainBean2可以正常访问