spring @Configuration和@Configurable的区别

@Configuration

  • 1.使用 @Configration 注解将该类声明为一个配置类。
  • 2.在 hello() 方法上添加 @Bean 注解则会往 Spring 容器中添加一个名为 hello 的 Bean,该 Bean 即为方法的返回值。
1
2
3
4
5
6
7
8
9
10
11
12
package com.example.demo.component;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MyConfigration {
    @Bean
    public String hello() {
        return "welcome to hangge.com";
    }
}

(2)下面我们在一个 Controller 中获取并使用这个 Bean,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.example.demo.controller;
 
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
    String hello;
 
    @GetMapping("/test")
    public String test() {
        return hello;
    }
}
 


转载请保留原文链接:https://www.hangge.com/blog/cache/detail_2506.html

@Configurable

现在假设,我们想在非Spring管理的类中使用依赖注入;
比如:手动new出来的对象,正常情况下,Spring是无法依赖注入的,这个时候可以使用@Configurable注解;

现在假设我们有如下代码:

  1.  
    public class CarSalon {
  2.  
        //...
  3.  
        public void testDrive() {
  4.  
            Car car = new Car();
  5.  
            car.startCar();
  6.  
        }
  7.  
    }
  8.  
     
  9.  
    @Component
  10.  
    public class Car {
  11.  
        @Autowired
  12.  
        private Engine engine;
  13.  
        @Autowired
  14.  
        private Transmission transmission;
  15.  
     
  16.  
        public void startCar() {
  17.  
            transmission.setGear(1);
  18.  
            engine.engineOn();
  19.  
            System.out.println("Car started");
  20.  
        }
  21.  
    }
  22.  
     
  23.  
    @Component
  24.  
    public class Engine {
  25.  
    //...
  26.  
    }
  27.  
     
  28.  
    @Component
  29.  
    public class Transmission {
  30.  
    //...
  31.  
    }


代码运行时,会把Null异常。因为正常情况下,Spring无法对new出来的对象进行依赖注入;

在此基础上,我们使用@Configurable注解进行修改,如下:

  1.  
    @Configurable(preConstruction = true)
  2.  
    @Component
  3.  
    public class Car {
  4.  
     
  5.  
        @Autowired
  6.  
        private Engine engine;
  7.  
        @Autowired
  8.  
        private Transmission transmission;
  9.  
     
  10.  
        public void startCar() {
  11.  
            transmission.setGear(1);
  12.  
            engine.engineOn();
  13.  
     
  14.  
            System.out.println("Car started");
  15.  
        }
  16.  
    }

讲解:
@Configurable(preConstruction = true) 这个注解的作用是:
告诉Spring在构造函数运行之前将依赖注入到对象中。

posted @ 2021-04-15 10:29  星云惊蛰  阅读(473)  评论(0)    收藏  举报