1.Java中@Autowired或@Resource这两个注解功能都是相同的,这两个注解的区别:@Autowired默认按类型装配,@Resource默认按名称装配,当找不到与名称匹配的bean时才会按类型装配。
2.@Autowired、@Qualifier、@Resource三者的区别:
简单理解:
@Autowired 默认根据类型注入;
@Resource 默认根据名字注入,其次按照类型注入;
@Autowired @Qualifier(“userService”) 两个结合起来默认按类型注入,其次按名字注入。
3.spring/springMVC中常用注解对比:
@Configuration — spring配置文件中的<beans></beans>
@Bean — spring配置文件中的<bean></bean>
@Autowired 、@Named 两个注解可以互换使用
@Component 、@Inject两个注解可以互换使用
@ContextConfiguration — spring整个配置文件(applicationContext.xml)
@componentScan — spring配置文件中的<context:component-scan base-package=“xxx”/>
@Service(“name”) — spring配置文件中的<bean class="xxx" id="name">
id=name
@Scope 代表spring容器的生命周期,取值有singleton、prototype 、request 、session 、global session五种。
注意:request、session和global session类型只实用于web程序,通常是和XmlWebApplicationContext共同使用。
@EnableScheduling:开启对定时任务的支持;
@Scheduled:声明一个定时任务;
@Conditional:满足一定条件来创建一个特定的bean;
@RequestHeader : 可以把Request请求header部分的值绑定到方法的参数上。
Request的Header部分:
Host localhost:8080
Accept text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(
@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
// ...
}
上面的代码,把request header部分的 Accept-Encoding的值,绑定到参数encoding上了, Keep-Alive header的值绑定到参数keepAlive上。
@CookieValue : 可以把Request header中关于cookie的值绑定到方法的参数上。
JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
//...
}
即把JSESSIONID的值绑定到参数cookie上。
@RequestParam :获取参数;SpringMVC获取后台控制层参数有两种:
1.request.getParameter(“属性名”); 2.@requestParam。
1.常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;
2.用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;
3.该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;
@Controller
@RequestMapping("/pets")
@SessionAttributes("pet")
public class EditPetForm {
// ...
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
Pet pet = this.clinic.loadPet(petId);
model.addAttribute("pet", pet);
return "petForm";
}
// ...
@RequestBody : 将HTTP请求正文转换为适合的HttpMessageConverter对象。[SpringMVC]
@ResponseBody :将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。[SpringMVC]
HttpMessageConverter接口,需要开启<mvc:annotation-driven />。
AnnotationMethodHandlerAdapter将会初始化7个转换器,可以通过调用AnnotationMethodHandlerAdapter的getMessageConverts()方法来获取转换器的一个集合 List<HttpMessageConverter>
引用:
ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter
@SessionAttributes:用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;
@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("pet")
public class EditPetForm {
// ...
}
@ModelAttribute:
该注解有两个用法,一个是用于方法上,一个是用于参数上;
用于方法上时: 通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;
用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:
1. @SessionAttributes 启用的attribute 对象上;
2.@ModelAttribute 用于方法上时指定的model对象;
3.上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。
用到方法上@ModelAttribute的示例代码:
// Add one attribute
// The return value of the method is added to the model under the name "account"
// You can customize the name via @ModelAttribute("myAccount")
@ModelAttribute
public Account addAccount(@RequestParam String number) {
return accountManager.findAccount(number);
}
这种方式实际的效果就是在调用@RequestMapping的方法之前,为request对象的model里put(“account”, Account);
用在参数上的@ModelAttribute示例代码:
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) {
//......
}
首先查询 @SessionAttributes有无绑定的Pet对象,若没有则查询@ModelAttribute方法层面上是否绑定了Pet对象,若没有则将URI template中的值按对应的名称绑定到Pet对象的各属性上。
问题:在不给定注解的情况下,参数是怎样绑定的?
通过分析AnnotationMethodHandlerAdapter和RequestMappingHandlerAdapter的源代码发现,方法的参数在不给定参数的情况下:
若要绑定的对象时简单类型: 调用@RequestParam来处理的。
若要绑定的对象时复杂类型: 调用@ModelAttribute来处理的。
这里的简单类型指java的原始类型(boolean, int 等)、原始类型对象(Boolean, Int等)、String、Date等ConversionService里可以直接String转换成目标对象的类型;
@PathVariable : 当使用@RequestMapping URI template 样式映射时, 即someUrl/{paramId}, 这时的paramId可通过@Pathvariable注解绑定它传过来的值到方法的参数上。[SpringMVC]
例如:
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
@RequestMapping("/pets/{petId}")
public void findPet(@PathVariable String ownerId,@PathVariable String petId, Model model) {
// implementation omitted
}
}
@SuppressWarnings(value=”unchecked”):用于抑制编译器产生警告信息。value默认为checked。
@PropertySource:注入配置文件;
@Value():读取参数;详细原理如下讲解:
@Value()需要的参数有两种形式:@Value("#{configProperties['t1.msgname']}")或者@Value("${t1.msgname}")
配置上的区别:
1.@Value("#{configProperties['t1.msgname']}")这种形式的配置中有“configProperties”,其实它指定的是配置文件的加载对象:配置如下:
<bean id="configProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:/config/t1.properties</value>
</list>
</property>
</bean>
这样配置就可完成对属性的具体注入了
2.@Value("${t1.msgname}")这种形式不需要指定具体加载对象,这时候需要一个关键的对象来完成PreferencesPlaceholderConfigurer,这个对象的配置可以利用上面配置1中的配置,也可以自己直接自定配置文件路径。
如果使用配置1中的配置,可以写成如下情况:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties" />
</bean>
如果直接指定配置文件的话,可以写成如下情况:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="location">
<value>config/t1.properties</value>
</property>
</bean>
@JmsListener:监听消费,实现了异步消费。
在官方文档中已经说明需要支持@JmsListener注解,则需要在任意@Configuration类添加@EnableJms注解,同时还需要配置DefaultJmsListenerContainerFactory的Bean实例:
Bean方式配置:
@Configuration
@EnableJms
public class GatewayActiveMQFactory extends AbstractActiveMQFactory {
//……
}
XML方式配置:
<jms:annotation-driven/>
<bean id="jmsListenerContainerFactory" class="org.springframework.jms.config.DefaultJmsListenerContainerFactory">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destinationResolver" ref="destinationResolver"/>
<property name="concurrency" ref="3-10"/>
</bean>
@EnableWs: 启动webservice。
Spring Boot整合spring-ws开发web service
1.添加依赖
spring boot的工程,除了spring boot外还需要添加spring-ws和wsdl4j的依赖,当然后面生成代码还需要添加maven的jaxb2插件。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.3</version>
</dependency>
2.编写schema文件
spring-ws的发布,都是以一个schema文件(xsd)定义开始的,它描述了web service的参数以及返回的数据。
下面是官方示例给出的countries.xsd,这里我们也以它为例,当然命名空间改掉了,因为等会jaxb2插件生成代码是以它来确定包名的:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema";
xmlns:tns="UpdateAppAcctSoap";//由程序员自己定义
targetNamespace="UpdateAppAcctSoap"; //由程序员自己定义
elementFormDefault="qualified">
<xs:element name="RequestInfo">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string" />
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name="ResponseInfo">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string" />
</xs:simpleContent>
</xs:complexType>
</xs:element>
<!--
<xs:element name="getCountryRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="getCountryResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="country" type="tns:country"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="country">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="population" type="xs:int"/>
<xs:element name="capital" type="xs:string"/>
<xs:element name="currency" type="tns:currency"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="currency">
<xs:restriction base="xs:string">
<xs:enumeration value="GBP"/>
<xs:enumeration value="EUR"/>
<xs:enumeration value="PLN"/>
</xs:restriction>
</xs:simpleType>
-->
</xs:schema>
3.添加maven的jaxb2插件来生成代码
jaxb2插件可以根据描述的xsd文件来帮我们生成相应的ws代码,具体配置如下:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>${project.basedir}/src/main/resources//schema</schemaDirectory>
<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</plugin>
配置好插件然后install一下,这样web service需要的服务端代码就已经帮我们生成好了,根据上面的xsd,生成的代码在相应的包下。
4.编写Endpoint
我们就不再像spring-ws官方那样再建一个Repository了,这里直接返回。需要注意PayloadRoot注解当中的namespace和localPart需要和xsd中对应。
@Endpoint
public class UpdateAppAcctSoap extends RestBase {
private static final String NAMESPACE_URI = "UpdateAppAcctSoap";
private final Logger logger = LoggerFactory.getLogger(UpdateAppAcctSoap.class);
@Autowired
HttpServletRequest request;
@Autowired
ILog iLog;
@Autowired
IUpdateAppAcctService appAcctService;
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "RequestInfo")
@ResponsePayload
public ResponseInfo doService(@RequestPayload RequestInfo requestInfo) {
iLog.info(logger, getTransNo(request), null, "", requestInfo);
String res = appAcctService.doService(requestInfo.getValue(), getTransNo(request));
ResponseInfo responseInfo = new ResponseInfo();
responseInfo.setValue(res);
return responseInfo;
}
}
【RequestInfo类的写法:】
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "RequestInfo", namespace = "UpdateAppAcctSoap")
public class RequestInfo {
@XmlValue
protected String value;
/**
* 获取value属性的值。
* @return
* possible object is
* {@link String }
*/
public String getValue() {
return value;
}
/**
* 设置value属性的值。
* @param value
* allowed object is
* {@link String }
*/
public void setValue(String value) {
this.value = value;
}
}
【ResponseInfo类的写法:】
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "ResponseInfo", namespace = "UpdateAppAcctSoap")
public class ResponseInfo {
@XmlValue
protected String value;
/**
* 获取value属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* 设置value属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
}
5.在spring boot中配置web service
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
@Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/webservice/*");
}
@Bean(name = "UpdateAppAcctSoap")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("UpdateAppAcctSoap");
wsdl11Definition.setLocationUri("/webservice");
wsdl11Definition.setTargetNamespace(Access4aConstants.NAMESPACE);
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
@Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("UpdateAppAcctSoap.xsd"));
}
}
到这里spring-ws的所有配置和工作都已经完成了,上面的DefaultWsdl11Definition 中的name默认就是发布的ws的访问路径。
4.Spirng中@PostConstruce和@PreDestroy详解:
这两个注解作用于Servlet生命周期的注解,实现Bean初始化之前和销毁之前的自定义操作。
API文档说明:
@PostConstruct 注释用于在依赖关系注入完成之后需要执行的方法上,以执行任何初始化。此方法必须在将类放入服务之前调用。支持依赖关系注入的所有类都必须支持此注释。即使类没有请求注入任何资源,用 PostConstruct 注释的方法也必须被调用。只有一个方法可以用此注释进行注释。应用 PostConstruct 注释的方法必须遵守以下所有标准:该方法不得有任何参数,除非是在 EJB 拦截器 (interceptor) 的情况下,根据 EJB 规范的定义,在这种情况下它将带有一个 InvocationContext 对象 ;该方法的返回类型必须为 void;该方法不得抛出已检查异常;应用 PostConstruct 的方法可以是 public、protected、package private 或 private;除了应用程序客户端之外,该方法不能是 static;该方法可以是 final;如果该方法抛出未检查异常,那么不得将类放入服务中,除非是能够处理异常并可从中恢复的 EJB。
使用@PostConstruce和@PreDestroy注解应注意:
- 只有一个方法可以使用此注释进行注解;
- 被注解方法不得有任何参数;
- 被注解方法返回值为void;
- 被注解方法不得抛出已检查异常;
- 被注解方法需是非静态方法;
此方法只会被执行一次;
Servlet执行流程图:
在具体Bean的实例化过程中,@PostConstruce注释的方法,会在构造方法之后,init()方法之前调用。
@PostConstruce主要应用在初始化Servlet时加载一些缓存数据。
注意:此注解会影响服务的启动时间;在启动时会扫描WEB-INF/classes的所有文件和WEB-INF/lib下的所有jar包。
5.@Controller和@RestContoller[SpringMVC] 区别:
官方文档:
@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
意思是:
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
例如:本来应该到success.jsp页面的,则其显示success.如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
@WiselyConfiguration注解相当于@Configuration + @ComponentScan
6.Enable*注解:
@EnableAspectJAutoProxy:开启对AspectJ自动代理的支持;
@EnableAsync:开启异步方法的支持;
@EnableScheduling:开启定时任务的支持;
@EnableWebMvc:开启Web MVC配置的支持;
@EnableConfigurationProperties:开启对@ConfigurationProperties注解配置Bean的支持;
@EnableJpaRespositories:开启对Spring Data JPA Repository的支持;
@EnableTransactionManagement:开启注解式事务的支持;
@EnableCaching:开启注解式的缓存支持;
@ActiveProfiles:声明活动的profile;
@Profile(“dev”):指定环境;
7.SpringMVC常用注解:
@ControllerAdvice:声明一个控制器建言(全局);l
@ExceptionHandler:全局处理控制器里的异常;
@InitBinder:定制WebDataBinder;