公司项目马上要进入重构阶段了,基本上确定了用spring cloud,很久没有接触微服务架构的学习和编码,感觉都很生疏了。所以,利用假期时间,先熟悉起来,以便后面重构项目能顺利些。本篇博客内容是记录下自己的搭建过程以及其中遇到的一些问题。 使用IDEA工具,搭建一个spring boot 应用也是非常简单的。新建项目的主要几步,截图如下: 一. IDEA创建项目 1. 使用spring Initializr 方式 2. 添加一些项目信息 3. 添加一些依赖,其中包括Lomok(提供实体类的get和set方法),web以及mysql数据库。 二. 完善项目结构及业务实现 1. 添加JPA依赖,以User为例,实现根据id查询用户信息逻辑。 2. 完善配置文件 以前用的都是properties形式的配置文件,而yml形式的配置文件看起来更加简洁。
# 端口号 server: port: 7900 # 数据库相关配置 spring: jpa: generate-ddl: false show-sql: true hibernate: ddl-auto: none # 数据源 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/uqi-user username: root password: 123456 # 日志 logging: level: root: INFO org.hibernate: INFO org.hibernate.type.descriptor.sql.BasicBinder: TRACE org.hibernate.type.descriptor.sql.BasicExtractor: TRACE com.springms: DEBUG3.业务主要代码: 1)Entity层,用户实体。
@Entity @Data @Table(name = "sys_user") @JsonIgnoreProperties(value = {"handler","hibernateLazyInitializer","fieldHandler"}) public class User implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String email; private String pwd; private String nickName; private Integer deleted; private Integer state; }2)Repository层,继承JpaRepository。
@Repository public interface UserRepository extends JpaRepository<User,Long> { }3)Service接口及实现层
public interface IUserService { public User findById(Long id); } @Service @Transactional public class UserServiceImpl implements IUserService { @Autowired private UserRepository userRepository; @Override public User findById(Long id) { return userRepository.getOne(id); } }4) Controller层
@RestController @RequestMapping("/uplus") public class UserController { @Autowired private UserServiceImpl userService; @GetMapping("/user/{id}") public User findById(@PathVariable Long id){ return this.userService.findById(id); } }三. 遇到的问题
1. spring boot不能注入JpaRepository接口,提示找不到bean,错误信息如下:
Field userRepository in com.uqiauto.cloud.UserController required a bean of type 'com.uqiauto.cloud.UserRepository' that could not be found. Action: Consider defining a bean of type 'com.uqiauto.cloud.UserRepository' in your configuration.解决方案:jpa包错误冲突,错误是因为项目引用的是spring中的jpa包而不是spring boot中的jpa包。
2. 根据id查询用户信息结果,提示json解析错误,错误信息如下:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.uqiauto.cloud.entity.User_$$_jvste9a_0["handler"])解决方案:根据提示可以知道,解析过程中提示handler字段出错,而实际上User实体中并未包含该字段,所以,在实体中,加上了一行注解,解析过程中会忽略一些字段,即:@JsonIgnoreProperties(value = {“handler”,”hibernateLazyInitializer”,”fieldHandler”})