1.软件下载
Eclipse:https://www.eclipse.org/downloads/packages/release/2018-09/r/eclipse-ide-java-ee-developers
Mango:https://www.mongodb.com/try/download/community
2.左侧工程一览区域,鼠标右键---->New----->Other...
image.png
3.选择Maven Project,下一步
image.png
4.直接下一步
image.png
5.Filter:org.apache.maven.archetypes,选择quickstart,下一步
如果catalog为All Catalogs,出现Retrieving archetypes,加载缓慢。那么catalog可以选择为Internal
image.png
6.输入以下内容,完成
Group Id 中输入项目的基本包名。
Artifact Id 中输入项目名。
7.配置POM
使用的各个组件的版本可以到下面的网站通过groupId和artifactId进行查找
https://repo.maven.apache.org/
<?xml version="1.0" encoding="UTF-8"?>
<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.co</groupId>
<artifactId>lanzy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<mybatis.spring.boot.version>1.2.0</mybatis.spring.boot.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.1.8.RELEASE</version>
<type>pom</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
8.左侧工程一览区域,右键工程----->Maven----->Update Project...
9.写点代码测试一下
目录结构:
image.png
MongoSampleController .java
package jp.co.api.controller;
import jp.co.api.entity.MongoSampleEntity;
import jp.co.api.service.MongoSampleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MongoSampleController {
private static Logger log = LoggerFactory.getLogger(MongoSampleController.class);
@Autowired
private MongoSampleService mss;
// @RequestMapping(value = "/add")
// @RequestMapping("/add/{param}")
// @PostMapping("/add")
@GetMapping(value = "/add")
public void saveTest() throws Exception {
log.info("saveTest start");
MongoSampleEntity mgtest = new MongoSampleEntity();
mgtest.setId(11);
mgtest.setAge(33);
mgtest.setName("lanzy");
mss.saveTest(mgtest);
log.info("saveTest end");
}
@GetMapping(value = "/find")
public MongoSampleEntity findTestByName() {
return mss.findTestByName();
}
@GetMapping(value = "/update")
public void updateTest() {
MongoSampleEntity mgtest = new MongoSampleEntity();
mgtest.setId(11);
mgtest.setAge(44);
mgtest.setName("lanzy");
mss.updateTest(mgtest);
}
@GetMapping(value = "/del")
public void deleteTestById() {
mss.deleteTestById(11);
}
}
MangoSampleDao.java
package jp.co.api.dao;
import jp.co.api.entity.MongoSampleEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
@Component
public class MangoSampleDao {
@Autowired
private MongoTemplate mongoTemplate;
public void saveTest(MongoSampleEntity test) {
mongoTemplate.save(test);
}
public MongoSampleEntity findTestByName(String name) {
Query query = new Query(Criteria.where("name").is(name));
MongoSampleEntity mgt = mongoTemplate.findOne(query, MongoSampleEntity.class);
return mgt;
}
public void updateTest(MongoSampleEntity test) {
Query query = new Query(Criteria.where("id").is(test.getId()));
Update update = new Update().set("age", test.getAge()).set("name", test.getName());
mongoTemplate.updateFirst(query, update, MongoSampleEntity.class);
// mongoTemplate.updateMulti(query,update,TestEntity.class);
}
public void deleteTestById(Integer id) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query, MongoSampleEntity.class);
}
}
MongoSampleEntity.java
package jp.co.api.entity;
public class MongoSampleEntity {
private Integer id;
private Integer age;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MongoSampleServiceImpl.java
package jp.co.api.service.impl;
import jp.co.api.dao.MangoSampleDao;
import jp.co.api.entity.MongoSampleEntity;
import jp.co.api.service.MongoSampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class MongoSampleServiceImpl implements MongoSampleService {
@Autowired
private MangoSampleDao mtdao;
@Transactional
public void saveTest(MongoSampleEntity mgtest) {
mtdao.saveTest(mgtest);
}
public MongoSampleEntity findTestByName() {
MongoSampleEntity mgtest = mtdao.findTestByName("lanzy");
System.out.println("mgtest is " + mgtest);
return mgtest;
}
@Transactional
public void updateTest(MongoSampleEntity mgtest) {
mtdao.updateTest(mgtest);
}
@Transactional
public void deleteTestById(Integer id) {
mtdao.deleteTestById(id);
}
}
MongoSampleService.java
package jp.co.api.service;
import jp.co.api.entity.MongoSampleEntity;
public interface MongoSampleService {
public void saveTest(MongoSampleEntity mgtest);
public MongoSampleEntity findTestByName();
public void updateTest(MongoSampleEntity mgtest);
public void deleteTestById(Integer id);
}
App.java
package jp.co.api;
import fw.log.LogNameReplacer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
/**
* XXX。
*
* @author Lanzy
*
*/
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class })
public class App {
public static void main(String[] args) {
String logName = "APILOG";
if (args != null && args.length > 0) {
logName = args[0];
}
System.setProperty(LogNameReplacer.LOG_NAME_KEY, logName.toUpperCase());
SpringApplication.run(App.class, args);
}
}
MongoTransactionConfig.java
package fw.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
@Configuration
public class MongoTransactionConfig {
@Bean
MongoTransactionManager transactionManager(MongoDbFactory factory) {
return new MongoTransactionManager(factory);
}
}
LogNameReplacer.java
package fw.log;
public class LogNameReplacer {
public static final String LOG_NAME_KEY = "LogName";
private static final String LOG_NAME = String.valueOf(System.getProperty(LOG_NAME_KEY));
private static final String LOG_NAME_TOKEN = "\\$LogName\\$";
public static String replaceLogName(String fileName) {
return fileName.replaceAll(LOG_NAME_TOKEN, LOG_NAME);
}
}
LogRollingFileAppender.java
package fw.log;
import ch.qos.logback.core.rolling.RollingFileAppender;
public class LogRollingFileAppender extends RollingFileAppender<Object> {
@Override
public String getFile() {
return LogNameReplacer.replaceLogName(super.getFile());
}
@Override
public void setFile(String fileName) {
super.setFile(LogNameReplacer.replaceLogName(fileName));
}
}
LogTimeBasedRollingPolicy.java
package fw.log;
import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
public class LogTimeBasedRollingPolicy extends SizeAndTimeBasedRollingPolicy<Object> {
@Override
public String getActiveFileName() {
String activeFileName = LogNameReplacer.replaceLogName(super.getActiveFileName());
return activeFileName;
}
@Override
public void setFileNamePattern(String fnp) {
super.setFileNamePattern(LogNameReplacer.replaceLogName(fnp));
}
}
application.yml
spring:
data:
mongodb:
uri: mongodb://localhost:27017/apitest
# 用户名密码:
# mongodb://【name】:【pass】@localhost:27017/test
# 多数据库:(中间用","分割)
# mongodb://192.168.1.1:20000,192.168.1.2:20000,192.168.252.12:20000/test
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="false" scanPeriod="30 minutes">
<property name="app.name" value="backend.api"/>
<property name="logback_level" value="INFO"/>
<property name="logback_rolling" value="true"/>
<property name="base_path" value="C:/workspace/log/api/"/>
<property name="rolling_path" value="C:/workspace/log/api/bak/"/>
<property name="logback_error" value="api_error"/>
<property name="logback_max_file_size" value="10MB"/>
<property name="logback_pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger %L -| %msg%n"/>
<appender name="APIXXXX_LOG" class="fw.log.LogRollingFileAppender">
<file>${base_path}$LogName$.log</file>
<rollingPolicy class="fw.log.LogTimeBasedRollingPolicy">
<fileNamePattern>${rolling_path}$LogName$_%d{yyyyMMdd}.%i.log</fileNamePattern>
<maxHistory>30</maxHistory>
<maxFileSize>${logback_max_file_size}</maxFileSize>
</rollingPolicy>
<encoder>
<pattern>${logback_pattern}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="ERROR_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${base_path}${logback_error}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${rolling_path}${logback_error}_%d{yyyyMMdd}.%i.log</fileNamePattern>
<maxHistory>30</maxHistory>
<maxFileSize>${logback_max_file_size}</maxFileSize>
</rollingPolicy>
<encoder>
<pattern>${logback_pattern}</pattern>
<charset>UTF-8</charset>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${logback_pattern}</pattern>
</encoder>
</appender>
<logger name="jp.co.api" level="${logback_level}" additivity="false">
<appender-ref ref="APIXXXX_LOG"/>
<appender-ref ref="ERROR_LOG"/>
<appender-ref ref="CONSOLE"/>
</logger>
</configuration>
10.启动:右键App.java----->Run As----->Java Application
11.打开浏览器测试一下
image.png
image.png
网友评论