简介
本文介绍Spring注册Bean的方法:@Configuration+@Bean。
注册Bean的方法我写了一个系列,见:Spring注册Bean(提供Bean)-方法大全 – 自学精灵
方法概述
写一个配置类,类上标记@Configuration。里边写一个方法,返回值为要注册的类,方法上加@Bean注解。
实例
要注册的类(Bean)
package com.knife.entity;
public class MyBean {
    public String sayHello() {
        return "Hello World";
    }
}
配置类
package com.knife.config;
import com.knife.entity.MyBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBeanConfiguration {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}
测试
package com.knife.controller;
import com.knife.entity.MyBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
    @Autowired
    private MyBean myBean;
    @GetMapping("/test")
    public String test() {
        return myBean.sayHello();
    }
}
结果


请先 !