最近项目中,需要提供接口服务,主要是使用Spark跑批量任务,web服务只提供简单接口来设置参数,以及启动、停止spark任务等,所以考虑使用spring-boot,也当做业余的一个学习。
作为一个spring-boot新手,网上找个例子来开始学习,遇到问题会慢慢的追加到本文中。
1. Spring-boot环境配置后,运行提示404
解决:404代表找不到访问地址,考虑是不是该url不存在或者敲错了,查证后没问题,那么下一个问题就是是不是spring并没有把相应的bean注册进去?
查看下,发现没有配置扫描的包,添加扫描包配置:
在入口类的@SpringBootApplication中添加scanBasePackages 配置具体的包:@SpringBootApplication(scanBasePackages = “com.pnlorf”)
重新启动,访问成功。
2. 使用spring-data-jpa访问数据库,启动报错
异常信息如下:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-05-15 09:59:37.292 ERROR 7016 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userRepository in com.pnlorf.controller.UserController required a bean of type 'com.pnlorf.dao.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.pnlorf.dao.UserRepository' in your configuration.
源代码如下:
Controller:
package com.pnlorf.controller;
import com.pnlorf.dao.UserRepository;
import com.pnlorf.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* description:
* author: pnlorf
* date: 2018/5/14
* package: com.pnlorf.controller
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@RequestMapping("queryAll")
@ResponseBody
public List<User> queryAll() {
List<User> list = userRepository.findAll();
return list;
}
}
UserRepository:
package com.pnlorf.dao;
import com.pnlorf.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* description:
* author: pnlorf
* date: 2018/5/14
* package: com.pnlorf.dao
*/
public interface UserRepository extends JpaRepository<User, String> {
}
User:
package com.pnlorf.model;
import javax.persistence.*;
import java.io.Serializable;
/**
* description:
* author: pnlorf
* date: 2018/5/14
* package: com.pnlorf.model
*/
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@Column(name = "id")
private String id;
@Column(name = "name")
private String name;
@Column(name = "password")
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
解决:google了一下,是说这种情况下,在Application入口类包下的都会被扫描,不然需要配置scanpackage,但是配置了扫描包没有生效(可能配置有问题吧),将SpringBootSparkGraphxApplication拿倒外层包,问题解决。
参考:
https://stackoverflow.com/questions/42907553/field-required-a-bean-of-type-that-could-not-be-found-error-spring-restful-ap?noredirect=1&lq=1