Spring注解(@Bean、@Resouce、@Autowired、@Component)

今天来说说 Spring中比较容易混淆的几个注解,说说他们的异同和各自的用法。
★相同点
它们都是Spring用来注入资源的注解。利用它们都可以向Spring注入一个对象。
★不同点及用法
(1)Bean
这是Spring注入Bean的注解,相当于xml中配置的Bean元素。由此可见他是基于Spring配置文件的注解。所以在使用时可以与@Configuration搭配使用。在容器启动时就创建Bean对象。也可以单独使用。在调用的时候再创建。

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.example.demo.service.UserService;
import com.example.demo.service.serviceImpl.UserServiceImpl;

@Configuration
public class AppConfig {
    
    public static void main(String[] args) {
    }
    
    @Bean
    public UserService userService() {
        UserService us = new UserServiceImpl();
        System.out.println(us.toString());
        return us;
    }

}

在UserService 中我们添加一个toString方法:

@Service("userService")
public class UserServiceImpl implements UserService {
    public String toString() {
        return "this is a bean create by @Bean";
    }

}

使用@Autowired注解将该Bean注入到Controller中

@RestController
public class UserController {
    @Autowired
    UserService userService;
      ......
}

启动服务器,可以看到控制台输出如下信息:

2018-06-07 23:01:33.921  INFO 5976 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-06-07 23:01:33.922  INFO 5976 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-06-07 23:01:33.922  INFO 5976 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-06-07 23:01:33.922  INFO 5976 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
this is a bean create by @Bean
2018-06-07 23:01:34.320  INFO 5976 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-06-07 23:01:34.624  INFO 5976 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@64e7619d: startup date [Thu Jun 07 23:01:31 CST 2018]; root of context hierarchy
2018-06-07 23:01:34.709  INFO 5976 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping

从这个例子也可以看出@Autowired的用法:Autowired用于在Spring启动时自动装载了一个AutowiredAnnotationBeanPostProcessor后置处理器去扫描程序中带有@Autowied、@Resource等注解的类。并装配给该对象属性。
在这里多说两句,关于@Bean注解加不加@Configuration的区别。我们可以尝试如下代码:

//代码1
@Configuration
public class AppConfig {
    
    public static void main(String[] args) {
    }
    
    @Bean
    public UserService userService() {
        UserService us = new UserServiceImpl();
        System.out.println("Spring 启动调用:"+us.toString());
        return us;
    }

}

//代码2
public class AppConfig {
    
    public static void main(String[] args) {
    }
    
    @Bean
    public UserService userService() {
        UserService us = new UserServiceImpl();
        System.out.println("Spring 启动调用:"+us.toString());
        return us;
    }
}

再在Controller中分别使用代码1和代码2注入userService Bean

@RestController
public class UserController {
    @Autowired
    UserService userService;
    
    @RequestMapping(value="/vLogin")
    public ModelAndView vLogin(HttpServletRequest request,Model model,String userName,String password) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/user/login.html");
        System.out.println("UserController :"+userService.toString());
        return mav;
    }
}

分别在Spring启动时和访问 vLogin 的时候观察控制台输出结果:

//代码1 启动时
2018-06-08 00:19:51.302  INFO 5468 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-06-08 00:19:51.302  INFO 5468 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
Spring 启动调用:this is a bean create by @Bean
2018-06-08 00:19:51.703  INFO 5468 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

//代码1 访问 vLogin
2018-06-08 00:24:50.321  INFO 5468 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2018-06-08 00:24:50.354  INFO 5468 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 33 ms
UserControllerthis is a bean create by @Bean

代码2在执行时在启动时并没有输出Spring 启动调用:this is a bean create by @Bean 而在访问 vLogin 时输出UserControllerthis is a bean create by @Bean。
我们在直观一点直接将AppConfig代码改为如下:

//代码1
@Configuration
public class AppConfig {
    
    public static void main(String[] args) {
    }

    @Bean
    public UserService userService() {
        return null;
    }

}

//代码2
public class AppConfig {
    
    public static void main(String[] args) {
    }
    
    @Bean
    public UserService userService() {
        return null;
    }

}

启动Spring时,输出如下:

//代码1    【RuntimeException】
***************************
APPLICATION FAILED TO START
***************************

Description:

Field userService in com.example.demo.cotroller.UserController required a bean of type 'com.example.demo.service.UserService' that could not be found.


Action:

Consider defining a bean of type 'com.example.demo.service.UserService' in your configuration.

//代码2
2018-06-08 00:37:06.107  INFO 6308 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-06-08 00:37:06.159  INFO 6308 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-06-08 00:37:06.168  INFO 6308 --- [           main] com.example.demo.FuckApplication         : Started FooApplication in 3.851 seconds (JVM running for 4.804)

由此可以看出:@ Bean注解和@Configuration搭配使用时,Spring会在容器启动时调用@Bean对应的方法创建一个Bean对象注入到Spring容器中。若创建失败,则抛出RuntimeException。@ Bean注解不和@Configuration搭配使用时,Spring不会在容器启动时调用@Bean对应的方法来创建Bean对象,而是在使用到给对象时在注入。

你可能感兴趣的:(Spring注解(@Bean、@Resouce、@Autowired、@Component))