`

SpringBoot学习笔记【二】-[SpringMvc+SpringTask+JPA集成开发]

 
阅读更多
一、SpringMvc
1. 新建HelloController.java
package cn.gov.zjport.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
	
	@RequestMapping("/hello")
	public String sayHello(String name) {
		return "hello ".concat(name);
	}

}


2.访问http://localhost:8080/hello?name=zjport



注意:
启动类一定要在Controller的包路径中,不能存在于同级的不同包中。

二、Spring Task
package cn.gov.zjport.demo.job;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class TestJob {
	private Logger logger=LoggerFactory.getLogger(this.getClass());
	
	@Scheduled(fixedRate = 10000)
    public void produce() {
		try {
			logger.info("test job run at "+ System.currentTimeMillis());
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
		}
    }
}





三、JPA访问数据库
1. pom文件增加
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.4.0</version>
		</dependency>


2. 编写DAO
package cn.gov.zjport.demo.dao.impl;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import cn.gov.zjport.demo.dao.TestDao;


@Repository
public class TestDaoImpl implements TestDao{
	
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	public String getSysdate(){
		return this.jdbcTemplate.queryForList("select to_char(sysdate,'yyyymmddHH24miss') as curTime from dual").get(0).get("curTime").toString();
	}
}



3. application.properties增加
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:zjport
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.max-idle=5
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5


4. Controller添加测试方法
package cn.gov.zjport.demo.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.gov.zjport.demo.dao.TestDao;

@RestController
public class HelloController {
	@Resource
	private TestDao testDao;
	
	@RequestMapping("/hello")
	public String sayHello(String name) {
		return "hello ".concat(name);
	}
	
	@RequestMapping("/access")
	public String access() {
		return "access at ".concat(testDao.getSysdate());
	}

}


5. 访问 http://localhost:8080/access


  • 大小: 14.1 KB
  • 大小: 112.9 KB
  • 大小: 11.2 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics