@Bean的用法

@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名

定义Bean

下面是@Configuration里的一个例子

@Configuration
public class AppConfig {

    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }

}

这个配置就等同于之前在xml里的配置

<beans>
    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
</beans>

@Configuration的作用和使用

从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
@Configuation等价于

<Beans></Beans>

@Component

@Component 等价于

<Bean></Bean>

@Bean VS @Component

  • 两个注解的结果是相同的,bean都会被添加到Spring上下文中。
  • @Component 标注的是类,允许通过自动扫描发现。
  • @Bean需要在配置类@Configuation中使用。
  • @Component类使用的方法或字段时不会使用CGLIB增强。而在@Configuration类中使用方法或字段时则使用CGLIB创造协作对象

@Controller/@RestController/@RequestMapping介绍

@Controller

@Controller 处理http请求

@Controller
//@ResponseBody
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

单独使用会报500错
在pom.xml文件中添加如下模块依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

springboot 游标 spring标签使用大全_字段


就可以看到hello.html中所呈现的内容了。

这里再templates文件下加入了hello.xml文件

然后我们加入@ResponseBody

@Controller
@ResponseBody
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

返回的结果是

springboot 游标 spring标签使用大全_字段_02


这里我们把

@Controller

@ResponseBody

换成

@RestController 后

运行结果

springboot 游标 spring标签使用大全_xml文件_03


也是一样的。说明@Controller+@ResponseBody的效果==@RerstController

@RequestMapping配置url映射

@RequestMapping此注解即可以作用在控制器的某个方法上,也可以作用在此控制器类上。
当控制器在类级别上添加@RequestMapping注解时,这个注解会应用到控制器的所有处理器方法上。处理器方法上的@RequestMapping注解会对类级别上的@RequestMapping的声明进行补充。
例一

@RestController
@RequestMapping("/h")
public class HelloController {

    @RequestMapping("/h1")
    public String sayHello(){
        return "hello";
    }
   
}

以上代码sayHello所响应的url=localhost:8080/h/h1

springboot 游标 spring标签使用大全_spring_04


例二

代码

@RestController
@RequestMapping("/h")
public class HelloController {

    @RequestMapping("/h1")
    public String sayHello(){
        return "hello";
    }
    @RequestMapping
    public String sayHi(){
        return "Hi";
    }

}

实现效果

springboot 游标 spring标签使用大全_xml文件_05


以上图片sayHi所响应的url=localhost:8080/h

从这两个方法所响应的url可以回过头来看这两句话:当控制器在类级别上添加@RequestMapping注解时,这个注解会应用到控制器的所有处理器方法上。处理器方法上的@RequestMapping注解会对类级别上的@RequestMapping的声明进行补充。

小结

本篇博文就介绍了下@Controller/@RestController/@RequestMappping几种常用注解。