Spring Registration Bean Series - Method 2: @Configuration+@Bean

Original website: Spring Register Bean Series--Method 2: @Configuration+@Bean_IT The blog of the sharp knife out of the sheath - CSDN blog

Introduction

        This article introduces the method of Spring registration Bean: @Configuration+@Bean.

         I wrote a series of methods for registering beans, see: Spring Registering Beans (Providing Beans) Series--Method Encyclopedia

Method overview

        Write a configuration class, marked @Configuration on the class. Write a method inside, the return value is the class to be registered, and add @Bean annotation to the method.

example

The class to be registered (Bean)

package com.knife.entity;

public class MyBean {
    public String sayHello() {
        return "Hello World";
    }
}

configuration class

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

test

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

result

Guess you like

Origin blog.csdn.net/feiying0canglang/article/details/126896421