This small java library is used with spring to use Annotations for HTTP Response Headers.
You can specifiy @HttpResponseHeader
and @HttpResponseHeaders
for methods and classes. If an annotation
is visible on method level it will ignore the class level one. If the class annotation provides the same
header key like a method annotation, the method annotation will override the value of the class annotation.
/* One Header */
@HttpResponseHeader(name="X-Key", value="X-Value-Method")
public String handleExtraAnnotatedMethod() {
return null;
}
/* Multiple headers */
@HttpResponseHeaders(
{
@HttpResponseHeader(name="X-Key-One", value="X-Value-One-Method"),
@HttpResponseHeader(name="X-Key-Two", value="X-Value-Two-Method")
}
)
public String handleMultipleExtraAnnotatedMethod() {
return null;
}
@HttpResponseHeader(name="X-Key-For-Response-Header", value="X-Value-For-Response-Header-Class")
@HttpResponseHeaders(
{
@HttpResponseHeader(name="X-Key-For-Response-Headers-One", value="X-Value-For-Response-Headers-One-Class"),
@HttpResponseHeader(name="X-Key-For-Response-Headers-Two", value="X-Value-For-Response-Headers-Two-Class")
}
)
@Controller
public class FullyAnnotatedTestController {
/* ... */
}
It's also possible, to use SpEL for
the name
and value
property.
To enable parsing for the value
property, enable it with valueExpression=true
.
For example:
@HttpResponseHeader(name="Cache-Control", value="#{'max-age=' + (60*5)}", valueExpression=true)
will result in:
Cache-Control: max-age=300
If you use that to read properties (like java.version
):
@HttpResponseHeader(name="X-Java-Version", value="#{environment.getProperty('java.version')}", valueExpression=true)
will result in:
X-Java-Version: 1.8.0_25
Replace VERSION with or 0.3.0-SNAPSHOT.
Maven:
<dependency>
<groupId>net.dracoblue.spring</groupId>
<artifactId>http-response-headers</artifactId>
<version>VERSION</version>
</dependency>
Gradle/Grails:
compile 'net.dracoblue.spring:http-response-headers:VERSION'
Add this to your SpringBootApplication:
@Autowired
HttpResponseHeaderHandlerInterceptor httpResponsHeaderHandlerInterceptor;
@Bean
public WebMvcConfigurer contentNegotiatorConfigurer()
{
return new WebMvcConfigurerAdapter()
{
@Override
public void addInterceptors(InterceptorRegistry registry)
{
registry.addInterceptor(httpResponsHeaderHandlerInterceptor);
}
};
}
This work is copyright by DracoBlue (http://dracoblue.net) and licensed under the terms of MIT License.