前言
SpringBoot推荐使用注解的方式去声明bean,但还是提供了xml的方式去加载bean
一.创建要声明为bean的实体类
WzqEntity.java
package com;
/**
* @description:
* @author: Wzq
* @create: 2019-12-12 15:44
*/
public class WzqEntity {
public String getStr(){
return "我是xml配置的bean!";
}
}
二.在resources下创建spring-bean.xml
spring-bean.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="wzqEntity" class="com.WzqEntity" ></bean>
</beans>
三.使用@ImportResource注解将xml配置bean加入spring ioc容器
config.java
package com.wzq.dome.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
/**
* @description:
* @author: Wzq
* @create: 2019-12-12 15:48
*/
@Configuration
@ImportResource(value = {"classpath:spring-bean.xml"})
public class config {
}
四.使用xml声明的bean
TestController.java
package com.wzq.dome.action;
import com.WzqEntity;
import com.wzq.dome.entity.ProFileEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description:
* @author: Wzq
* @create: 2019-12-12 10:27
*/
@RestController
public class TestController {
@Autowired
WzqEntity wzqEntity;
@RequestMapping("/test")
public String test(){
return wzqEntity.getStr();
}
}