@contextconfigurationn和@component之间的区别

博客分类:
与SpringSecurity的配置类似,spring同样为我们提供了一个实现类WebMvcConfigurationSupport和一个注解@EnableWebMvc以帮助我们减少bean的声明。
applicationContext-MvcConfig.xml
&!-- 启用注解,并定义组件查找规则 ,mvc层只负责扫描@Controller --&
&context:component-scan base-package="web.function"
use-default-filters="false"&
&context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" /&
&/context:component-scan&
&!-- 视图处理器 --&
&bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"&
&property name="prefix" value="/WEB-INF/views/jsp/function/" /&
&property name="suffix" value=".jsp" /&
&!-- 定义国际化资源文件查找规则 ,各种messages.properties --&
&bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="config.messages.messages"&
&!-- servlet适配器,这里必须明确声明,因为spring默认没有初始化该适配器 --&
&bean id="servletHandlerAdapter"
class="org.springframework.web.servlet.handler.SimpleServletHandlerAdapter" /&
&!-- 定义文件上传处理器 --&
&bean id="multipartResolver"
class="org.springframework.monsMultipartResolver"
p:defaultEncoding="UTF-8" /&
&!-- 异常处理器 --&
&bean id="exceptionResolver" class="web.core.CP_SimpleMappingExceptionResolver"&
&property name="defaultErrorView" value="common_error" /&
&property name="exceptionAttribute" value="exception" /&
&property name="exceptionMappings"&
&prop key="java.lang.RuntimeException"&common_error&/prop&
&/property&
&!-- 定义公共参数初始化拦截器 --&
&bean id="initInterceptor" class="web.core.CP_InitializingInterceptor" /&
&!-- 本地化资源处理器 --&
&bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver" /&
&!-- 定义本地化变更拦截器 --&
&bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /&
&!-- 请求拦截器,每一个用户请求都会被拦截 --&
&mvc:interceptors&
&ref bean="localeChangeInterceptor" /&
&ref bean="initInterceptor" /&
&/mvc:interceptors&
&!-- 定义注解驱动Controller方法处理适配器 ,注:该适配器必须声明在&mvc:annotation-driven /&之前,否则不能正常处理参数类型的转换 --&
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"&
&property name="webBindingInitializer"&
&bean class="web.core.CP_PropertyEditorRegistrar"&
&property name="format" value="yyyy-MM-dd"&&/property&
&/property&
&property name="messageConverters"&
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" /&
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /&
&/property&
&!-- 会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter
两个bean,是spring MVC为@Controllers分发请求所必须的。 并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson) --&
&mvc:annotation-driven /&
&!-- 资源访问处理器 --&
&mvc:resources mapping="/static/**" location="/WEB-INF/static/" /&
MvcConfig.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "web.function", useDefaultFilters = false, includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class})
public class MvcConfig extends WebMvcConfigurationSupport {
private static final Logger logger = Logger
.getLogger(MvcConfig.class);
* 描述 : &注册试图处理器&. &br&
&使用方法说明&
public ViewResolver viewResolver() {
("ViewResolver");
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/jsp/function/");
viewResolver.setSuffix(".jsp");
return viewR
* 描述 : &注册消息资源处理器&. &br&
&使用方法说明&
public MessageSource messageSource() {
("MessageSource");
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("config.messages.messages");
return messageS
* 描述 : &注册servlet适配器&. &br&
&只需要在自定义的servlet上用@Controller("映射路径")标注即可&
public HandlerAdapter servletHandlerAdapter(){
("HandlerAdapter");
return new SimpleServletHandlerAdapter();
* 描述 : &本地化拦截器&. &br&
&使用方法说明&
public LocaleChangeInterceptor localeChangeInterceptor(){
("LocaleChangeInterceptor");
return new LocaleChangeInterceptor();
* 描述 : &基于cookie的本地化资源处理器&. &br&
&使用方法说明&
@Bean(name="localeResolver")
public CookieLocaleResolver cookieLocaleResolver(){
("CookieLocaleResolver");
return new CookieLocaleResolver();
* 描述 : &注册自定义拦截器&. &br&
&使用方法说明&
public CP_InitializingInterceptor initializingInterceptor(){
("CP_InitializingInterceptor");
return new CP_InitializingInterceptor();
* 描述 : &RequestMappingHandlerMapping需要显示声明,否则不能注册自定义的拦截器&. &br&
&这个比较奇怪,理论上应该是不需要的&
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
("RequestMappingHandlerMapping");
return super.requestMappingHandlerMapping();
* 描述 : &添加拦截器&. &br&
&使用方法说明&
* @param registry
protected void addInterceptors(InterceptorRegistry registry) {
// TODO Auto-generated method stub
("addInterceptors start");
registry.addInterceptor(localeChangeInterceptor());
registry.addInterceptor(initializingInterceptor());
("addInterceptors end");
* 描述 : &HandlerMapping需要显示声明,否则不能注册资源访问处理器&. &br&
&这个比较奇怪,理论上应该是不需要的&
public HandlerMapping resourceHandlerMapping() {
("HandlerMapping");
return super.resourceHandlerMapping();
* 描述 : &资源访问处理器&. &br&
&可以在jsp中使用/static/**的方式访问/WEB-INF/static/下的内容&
* @param registry
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
("addResourceHandlers");
registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/static/");
* 描述 : &文件上传处理器&. &br&
&使用方法说明&
@Bean(name="multipartResolver")
public CommonsMultipartResolver commonsMultipartResolver(){
("CommonsMultipartResolver");
return new CommonsMultipartResolver();
* 描述 : &异常处理器&. &br&
&系统运行时遇到指定的异常将会跳转到指定的页面&
@Bean(name="exceptionResolver")
public CP_SimpleMappingExceptionResolver simpleMappingExceptionResolver(){
("CP_SimpleMappingExceptionResolver");
CP_SimpleMappingExceptionResolver simpleMappingExceptionResolver= new CP_SimpleMappingExceptionResolver();
simpleMappingExceptionResolver.setDefaultErrorView("common_error");
simpleMappingExceptionResolver.setExceptionAttribute("exception");
Properties properties = new Properties();
properties.setProperty("java.lang.RuntimeException", "common_error");
simpleMappingExceptionResolver.setExceptionMappings(properties);
return simpleMappingExceptionR
* 描述 : &RequestMappingHandlerAdapter需要显示声明,否则不能注册通用属性编辑器&. &br&
&这个比较奇怪,理论上应该是不需要的&
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
("RequestMappingHandlerAdapter");
return super.requestMappingHandlerAdapter();
* 描述 : &注册通用属性编辑器&. &br&
&这里只增加了字符串转日期和字符串两边去空格的处理&
protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() {
("ConfigurableWebBindingInitializer");
ConfigurableWebBindingInitializer initializer = super.getConfigurableWebBindingInitializer();
CP_PropertyEditorRegistrar register = new CP_PropertyEditorRegistrar();
register.setFormat("yyyy-MM-dd");
initializer.setPropertyEditorRegistrar(register);
:代码下载
浏览 61423
hanqunfeng
浏览: 1227517 次
来自: 北京
您好,我用您的方法通过java api往jira系统中添加is ...
可以了,是因为没加intercept-url 的拦截, 尼玛, ...
请问为什么我配了security.xml后切入点不起作用(之前 ...
根据楼主的代码 继承了WebMvcConfigurationS ...
MvcConfig.java的FilterType.ANNOT ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'spring boot 的常用注解使用小结
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了spring boot 的常用注解使用小结,需要的朋友可以参考下
@RestController和@RequestMapping注解
4.0重要的一个新的改进是@RestController注解,它继承自@Controller注解。4.0之前的版本,Spring MVC的组件都使用@Controller来标识当前类是一个控制器servlet。使用这个特性,我们可以开发REST服务的时候不需要使用@Controller而专门的@RestController。
&当你实现一个RESTful web services的时候,response将一直通过response body发送。为了简化开发,Spring 4.0提供了一个专门版本的controller。下面我们来看看@RestController实现的定义:
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController
@RequestMapping 注解提供路由信息。它告诉Spring任何来自"/"路径的HTTP请求都应该被映射到 home 方法。 @RestController 注解告诉Spring以字符串的形式渲染结果,并直接返回给调用者。
注: @RestController 和 @RequestMapping 注解是Spring MVC注解(它们不是Spring Boot的特定部分)
@EnableAutoConfiguration注解
第二个类级别的注解是 @EnableAutoConfiguration 。这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于 spring-boot-starter-web 添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。Starter POMs和Auto-Configuration:设计auto-configuration的目的是更好的使用"Starter POMs",但这两个概念没有直接的联系。你可以自由地挑选starter POMs以外的jar依赖,并且Spring Boot将仍旧尽最大努力去自动配置你的应用。
你可以通过将 @EnableAutoConfiguration 或 @SpringBootApplication 注解添加到一个 @Configuration 类上来选择自动配置。
注:你只需要添加一个 @EnableAutoConfiguration 注解。我们建议你将它添加到主 @Configuration 类上。
如果发现应用了你不想要的特定自动配置类,你可以使用 @EnableAutoConfiguration 注解的排除属性来禁用它们。
&pre name="code" class="java"&import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
&pre name="code" class="java"&import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
@Configuration
Spring Boot提倡基于Java的配置。尽管你可以使用一个XML源来调用 SpringApplication.run() ,我们通常建议你使用 @Configuration 类作为主要源。一般定义 main 方法的类也是主要 @Configuration 的一个很好候选。你不需要将所有的 @Configuration 放进一个单独的类。 @Import 注解可以用来导入其他配置类。另外,你也可以使用 @ComponentScan 注解自动收集所有的Spring组件,包括 @Configuration 类。
如果你绝对需要使用基于XML的配置,我们建议你仍旧从一个 @Configuration 类开始。你可以使用附加的 @ImportResource 注解加载XML配置文件。
@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean
@ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)})
@ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)})
@SpringBootApplication
很多Spring Boot开发者总是使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 注解他们的main类。由于这些注解被如此频繁地一块使用(特别是你遵循以上最佳实践时),Spring Boot提供一个方便的 @SpringBootApplication 选择。
该 @SpringBootApplication 注解等价于以默认属性使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 。
package com.example.
import org.springframework.boot.SpringA
import org.springframework.boot.autoconfigure.SpringBootA
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
package com.example.
import org.springframework.boot.SpringA
import org.springframework.boot.autoconfigure.SpringBootA
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
Spring Boot将尝试校验外部的配置,默认使用JSR-303(如果在classpath路径中)。你可以轻松的为你的@ConfigurationProperties类添加JSR-303 javax.validation约束注解:
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private InetAddress remoteA
// ... getters and setters
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private InetAddress remoteA
// ... getters and setters
Spring Profiles提供了一种隔离应用程序配置的方式,并让这些配置只能在特定的环境下生效。任何@Component或@Configuration都能被@Profile标记,从而限制加载它的时机。
[java] view plain copy print?在CODE上查看代码片派生到我的代码片
@Configuration
@Profile("production")
public class ProductionConfiguration {
@Configuration
@Profile("production")
public class ProductionConfiguration {
}@ResponseBody
表示该方法的返回结果直接写入HTTP response body中
一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上
@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如
异步获取json数据,加上@responsebody后,会直接返回json数据。
@Component:
泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。一般公共的方法我会用上这个注解
@AutoWired
byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构
造函数进行标注,完成自动装配的工作。
当加上(required=false)时,就算找不到bean也不报错。
@RequestParam:
用在方法的参数前面。
@RequestParam String a =request.getParameter("a")。
@RequestParam String a =request.getParameter("a")。
@PathVariable:
路径变量。
RequestMapping("user/get/mac/{macAddress}")
public String getByMacAddress(@PathVariable String macAddress){
RequestMapping("user/get/mac/{macAddress}")
public String getByMacAddress(@PathVariable String macAddress){
参数与大括号里的名字一样要相同。
以上注解的示范
* 用户进行评论及对评论进行管理的 Controller 类;
@Controller
@RequestMapping("/msgCenter")
public class MyCommentController extends BaseController {
@Autowired
CommentService commentS
@Autowired
OperatorService operatorS
* 添加活动评论;
* @param applyId 活动 ID;
* @param content 评论内容;
@ResponseBody
@RequestMapping("/addComment")
public Map&String, Object& addComment(@RequestParam("applyId") Integer applyId, @RequestParam("content") String content) {
* 用户进行评论及对评论进行管理的 Controller 类;
@Controller
@RequestMapping("/msgCenter")
public class MyCommentController extends BaseController {
@Autowired
CommentService commentS
@Autowired
OperatorService operatorS
* 添加活动评论;
* @param applyId 活动 ID;
* @param content 评论内容;
@ResponseBody
@RequestMapping("/addComment")
public Map&String, Object& addComment(@RequestParam("applyId") Integer applyId, @RequestParam("content") String content) {
@RequestMapping("/list/{applyId}")
public String list(@PathVariable Long applyId, HttpServletRequest request, ModelMap modelMap) {
@RequestMapping("/list/{applyId}")
public String list(@PathVariable Long applyId, HttpServletRequest request, ModelMap modelMap) {
全局处理异常的:
@ControllerAdvice:
包含@Component。可以被扫描到。
统一处理异常。
@ExceptionHandler(Exception.class):
用在方法上面表示遇到这个异常就执行以下方法。
* 全局异常处理
@ControllerAdvice
class GlobalDefaultExceptionHandler {
public static final String DEFAULT_ERROR_VIEW = "error";
@ExceptionHandler({TypeMismatchException.class,NumberFormatException.class})
public ModelAndView formatErrorHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("error","参数类型错误");
mav.addObject("exception", e);
mav.addObject("url", RequestUtils.getCompleteRequestUrl(req));
mav.addObject("timestamp", new Date());
mav.setViewName(DEFAULT_ERROR_VIEW);
* 全局异常处理
@ControllerAdvice
class GlobalDefaultExceptionHandler {
public static final String DEFAULT_ERROR_VIEW = "error";
@ExceptionHandler({TypeMismatchException.class,NumberFormatException.class})
public ModelAndView formatErrorHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("error","参数类型错误");
mav.addObject("exception", e);
mav.addObject("url", RequestUtils.getCompleteRequestUrl(req));
mav.addObject("timestamp", new Date());
mav.setViewName(DEFAULT_ERROR_VIEW);
通过@value注解来读取application.properties里面的配置
# face++ key
face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR****
face_api_secret =D9WUQGCYLvOCIdsbX35uTH********
# face++ key
face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR****
face_api_secret =D9WUQGCYLvOCIdsbX35uTH********
@Value("${face_api_key}")
private String API_KEY;
@Value("${face_api_secret}")
private String API_SECRET;
@Value("${face_api_key}")
private String API_KEY;
@Value("${face_api_secret}")
private String API_SECRET;所以一般常用的配置都是配置在application.properties文件的
以上所述是小编给大家介绍的spring boot 的常用注解使用小结,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 java configuration 的文章

 

随机推荐