1. 程式人生 > 實用技巧 >@ImportResource-SpringBoot使用xml配置Bean

@ImportResource-SpringBoot使用xml配置Bean

前言

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();
    }

}

五.成功