不要到处都使用@Autowired啦

406 阅读1分钟

相信大部分人项目只要用了spring框架,肯定到处都是@Autowired或者@Resource。 注意: spring4.3以后就可以省略@Autowired了,全部更新内容: 地址;其中更新内容如下

img

这是什么意思呢,翻译过来“如果目标bean只定义一个构造函数,则不再需要指定@autowired注释。”;

我们平时开发中的bean大部分都不写构造函数,系统默认一个无参构造函数,这就符合这一条件。

看看下面这个例子:

Service

@Service
public class TestService {

    public void hello() {
        System.out.println("service say hello");
    }
}

Controller(使用@autowired)

@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/hello")
    public void hello() {
        System.out.println("controller say hello");
        testService.hello();
    }
}

//输出
controller say hello
service say hello

Controller(不使用@autowired)

@RestController
public class TestController {

    private TestService testService;

    public TestController(TestService testService) {
        this.testService = testService;
    }

    @GetMapping("/hello")
    public void hello() {
        System.out.println("controller say hello");
        testService.hello();
    }
}

//输出
controller say hello
service say hello

通过上面示例可以看出,不使用注解照样可以将spring中的bean注入到Controller中,但是,不使用注解的话,可能要多写一个构造方法,那有什么方法省去这个构造方法呢?

我们可以使用一个非常好用的插件:Lombok

@RestController
@AllArgsConstructor
public class TestController {

    private TestService testService;

    @GetMapping("/hello")
    public void hello() {
        System.out.println("controller say hello");
        testService.hello();
    }
}

//输出
controller say hello
service say hello

通过@AllArgsConstructor这个注解,可以省去全参数的构造方法,代码是不是简洁了很多。

Lombok还有很多其他用法,省去实体类的getset方法、省去定义日志对象等等,有兴趣的可以去深入了解一下。