Jersey請求springboot


一、理解springboot的bean裝載規則


      SpringBoot項目的Bean裝配默認規則是根據Application類所在的包位置從上往下掃描!
“Application類”是指SpringBoot項目入口類。這個類的位置很關鍵:
    如果Application類所在的包爲:com.boot.app,則只會掃描com.boot.app包及其所有子包,如果service或dao所在包不在com.boot.app及其子包下,則不會被掃描!即把Application類放到dao、service所在包的上級,com.boot.Application即可自動掃描。


二、Jersey請求springboot

    pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.tanjie</groupId>
	<artifactId>springboot_restful</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot_restful</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.2.RELEASE</version>
		<relativePath />
	</parent>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- springboot web支持 mvc/aop -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- 緩存服務,定時任務 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
		<!-- 實現類文件熱部署(類文件修改後不會立即生效), 實現對屬性文件的熱部署。 即devtools會監聽classpath下的文件變動,並且會立即重啓應用(發生在保存時機), 
			注意:因爲其採用的虛擬機機制,該項重啓是很快的 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
			<scope>true</scope>
		</dependency>
		<!-- spring data jpa -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<!-- restful jersey -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jersey</artifactId>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
		</dependency>
		<!-- 使用jerset-client模擬請求 -->
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-client</artifactId>
			<version>2.22.2</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-json-jackson</artifactId>
		</dependency>
		<!-- mysql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-Java</artifactId>
			<version>5.1.34</version>
		</dependency>
		<!-- JAXB -->
		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.2.3</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<!-- spring boot編譯插件 -->
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<!-- <executions> <execution> <goals> <goal>repackage</goal> </goals> 
					</execution> </executions> -->
				<!-- <dependencies> <dependency> <groupId>org.springframework</groupId> 
					<artifactId>springloaded</artifactId> <version>1.2.5.RELEASE</version> </dependency> 
					</dependencies> -->
				<configuration>
					<fork>true</fork>
				</configuration>
			</plugin>
		</plugins>
		<pluginManagement>
			<!-- 配置jdk版本 -->
			<plugins>
				<plugin>
					<artifactId>maven-compiler-plugin</artifactId>
					<configuration>
						<source>1.7</source>
						<target>1.7</target>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

     springboot項目啓動類

   

package com.tanjie;

import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.tanjie.springboot_restful.resources.JerseyConfig;

@SpringBootApplication
public class AppMian {

	@Bean
	public ServletRegistrationBean jerseyServlet() {
		ServletRegistrationBean registrationBean = new ServletRegistrationBean(
				new ServletContainer(), "/restful/*");
		registrationBean.addInitParameter(
				ServletProperties.JAXRS_APPLICATION_CLASS,
				JerseyConfig.class.getName());
		return registrationBean;
	}

	public static void main(String[] args) {
		SpringApplication.run(AppMian.class, args);
	}
}

     JerseyConfig


   

package com.tanjie.springboot_restful.resources;

import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;

@Component
public class JerseyConfig extends ResourceConfig {

	public JerseyConfig() {
		register(JacksonFeature.class);
		packages("com.tanjie");
	}
}

     資源類

  

package com.tanjie.springboot_restful.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tanjie.springboot_restful.service.UserService;
import com.tanjie.springboot_restful.vo.User;

@Path("/userResource")
@Component
public class UserResource {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(UserResource.class);

	@Autowired
	private UserService userService;

	@GET
	@Path("/save")
	@Produces(MediaType.APPLICATION_JSON)
	public String saveUser() {
		User user = new User();
		user.setName("zs");
		userService.saveUser(user);
		LOGGER.info("保存成功!");
		return "SUCCESS";
	}
}

    Servcie

 

package com.tanjie.springboot_restful.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tanjie.springboot_restful.dao.UserDao;
import com.tanjie.springboot_restful.vo.User;

@Service("userService")
public final class UserService implements IUserService{

	@Autowired
	private transient UserDao userDao;

	public void saveUser(User user) {
		userDao.save(user);
	}
}
    dao

  

package com.tanjie.springboot_restful.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.tanjie.springboot_restful.vo.User;

public interface UserDao  extends JpaRepository<User, Integer>{

}

    單元測試

  

package com.tanjie.springboot_restful;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;

import org.junit.Assert;
import org.junit.Test;

public class UserResourceTest {

	@Test
	public void test() {
		Client client = ClientBuilder.newClient();
		WebTarget target = client
				.target("http://localhost:8080/restful/userResource/save");
		String result = target.request().get(String.class);
		Assert.assertEquals("SUCCESS", result);
	}

}

    application.properties配置

    

# spring boot\u914D\u7F6E
#server.port=8888
#server.context-path=/helloboot
#user.name=zs
#user.age=18
#server.profiles.active=dev

#mysql datasource config
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

#JAVA Persistence API
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
spring.jpa.generate-ddl=true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
#[org.hibernate.cfg.ImprovedNamingStrategy  #org.hibernate.cfg.DefaultNamingStrategy]
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect


#redis config
#spring.redis.database=0
#spring.redis.host=127.0.0.1
#spring.redis.port=6379
#spring.redis.pool.max-idle=8
#spring.redis.pool.min-idle=0
#spring.redis.pool.max-active=8
#spring.redis.pool.max-wait=-1

#logback

#logging.file=D:/mylog/log.log
#logging.level.org.springframework.web=DEBUG

     運行效果

   

Hibernate: insert into user (name) values (?)
2017-01-07 15:17:03.947  INFO 1516 --- [nio-8080-exec-1] c.t.s.resources.UserResource:保存成功
發佈了40 篇原創文章 · 獲贊 36 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章