SpringBoot使用记录

项目结构


 

一:实体类 (Entity)

  1. @Entity~标注为实体类
  2. @Table(name = "数据库中表名")~对应数据库表
  3. @Id~标注该字段为id
  4. @GeneratedValue(strategy=GenerationType.IDENTITY)~id自增标注
  5. @Column(name="数据库中字段名称")~对应数据库中的字段
@Entity
@Table(name = "mini_user")
public class UserEntity {
	@Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="id")
	private Long id;
	
	@Column(name = "openid")
	private String openId;//用户唯一标识
	
	@Column(name = "nick_name")
	private String nickName;//用户昵称
	
	@Column(name = "avatar_url")
	private String avatarUrl;//用户头像
	
	@Column(name = "gender")
	private String gender;//性别

    get/set...
}

 

二:Dao层

  1. interface~dao层是接口层,主要对接数据库操作
  2. extends CrudRepository<实体类, Id类型>~继承CrudRepository里面有简单的crud操作
  3. @Query("写hql语句")~写数据库操作语句hql语句或sql语句,区别在nativeQuery=true为sql,不写则为hql
  4. @Modifying , @Transactional~删除和修改数据库操作时需要加这两个注释,保证操作事务性
public interface UserDao extends CrudRepository<UserEntity, Long>{

	@Query("from UserEntity where openId = ?")
	UserEntity findUserByOpenId(String openid);

        @Query("seletc * from user where openId = ?",nativeQuery=true)
	UserEntity findUserByOpenId(String openid);

        @Modifying
	@Transactional
	@Query("delete from UserEntity where openId = ?")
	void deleteUser(String openId);

}

 

三:service层

  1. @Service~标注该class为服务层,链接控制层和数据库操作的dao层
  2. @Autowired~通过spring自动注入相应的dao层
@Service
public class UserService{

	@Autowired
	private UserDao userDao;
	
	/**
	 * 保存用户信息
	 * @param user
	 */
	public void save(UserEntity user){
		userDao.save(user);
    }


	/**
	 * 通过openid获取用户对象
	 * @param openid
	 * @return
	 */
	public UserEntity findUserByOpenId(String openid) {
		return userDao.findUserByOpenId(openid);
	}

}

 

 四:控制层(Controller)

  1. @RestController~标注该class为控制层,并说明所有方法的返回值均不是jsp或任何页面
  2. @Controller~标注该class为控制层,并说明返回值为页面地址
  3. @RequestMapping("主映射地址")~定下进这个控制器的主映射地址例如:/test/user
  4. @Value("${配置文件中的属性名}")~可以将配置文件中的值引入该类直接使用
  5. @Autowired~让spring自动注入需要的服务层即service层,@Autowired private UserService userService;
  6. @RequestMapping(value = "对应方法映射", method = RequestMethod.GET)~通过url找到运行该类中的哪一个方法,/add
@RestController
@RequestMapping("${basepath}/user")
public class UserController {
	
	public static Logger logger = LogManager.getLogger(UserController.class);
	
	@Value("${wx.appid}")
	private String appid;
	
	@Value("${wx.secret}")
	private String secret;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private PictureUploadService pictureUploadService;
	
	/**
	 * 接收小程序传过来的登录code,返回对应的openid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/receiveCode", method = RequestMethod.GET)
	public String receiveCode(HttpServletRequest request, @RequestParam String loginCode){
		logger.info("请求成功,传过来的登录码为:" + loginCode);
		//请求微信服务器端去获取openid和sessionkey
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("appid", appid);
		params.put("secret", secret);
		params.put("js_code", loginCode);
		params.put("grant_type", "authorization_code");
		
		String ret = HttpAccess.getNameValuePairRequest(url, params, "utf-8", "authorization_code");
		
		JSONObject retJson = JSONObject.parseObject(ret);
		String openid = retJson.getString("openid");
		return openid;
	}
}

 五:配置文件 (application.properties)

  1. 项目运行端口配置
  2. server.port=8084

    任意属性配置

  3. 属性名=值

    数据源配置

  4. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/数据库名
    spring.datasource.username=账号
    spring.datasource.password=密码
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    spring.datasource.initialSize=5  
    spring.datasource.minIdle=5  
    spring.datasource.maxActive=20  
    spring.datasource.maxWait=60000  
    spring.datasource.timeBetweenEvictionRunsMillis=60000  
    spring.datasource.minEvictableIdleTimeMillis=300000  
    spring.datasource.validationQuery=SELECT 1 FROMDUAL  
    spring.datasource.testWhileIdle=true  
    spring.datasource.testOnBorrow=false  
    spring.datasource.testOnReturn=false  
    spring.datasource.poolPreparedStatements=true  
    spring.datasource.maxPoolPreparedStatementPerConnectionSize=20  
    spring.datasource.filters=stat,wall,log4j  
    spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # Specify the DBMS
    spring.jpa.database=MYSQL
    # Show or not log for each sql query
    spring.jpa.show-sql=true
    # Hibernate ddl auto (create, create-drop, update)
    spring.jpa.hibernate.ddl-auto=update
    # stripped before adding them to the entity manager)
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

    上传文件大小控制

  5. spring.http.multipart.maxFileSize=100Mb
    spring.http.multipart.maxRequestSize=100Mb

    配置直接访问本地数据

    spring.mvc.static-path-pattern=/**
    spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:本地地址

     

 


六:日志配置文件(log4j2.xml)

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
  <Appenders>
    <Console name="console" target="SYSTEM_OUT">
      <PatternLayout pattern="[%d{yyyy-MM-dd HH:mm:ss}][%p][%class.%method() %L] : %m%n"/>
    </Console>
    <RollingFile name="logfile" fileName="D://counts_log/jar-logs/app.log" filePattern="D://counts_log/jar-logs/%d{yyyy-MM-dd-HH}.log">
    	<PatternLayout pattern="[%d{yyyy-MM-dd HH:mm:ss}][%p][%class.%method() %L] : %m%n"/>
      	<Policies>  
        	<TimeBasedTriggeringPolicy interval="1" modulate="true"/> 
        </Policies> 
    </RollingFile>
  </Appenders>
  <Loggers>
    <Root level="info">
      <!-- <AppenderRef ref="database"/> -->
      <AppenderRef ref="console"/>
      <AppenderRef ref="logfile"/>
    </Root>
    <logger name="com.gargoylesoftware.htmlunit" level="fatal" additivity="false"/>
  </Loggers>
</Configuration>

 


 

常用jar包

    <!-- logging begin -->
    <dependency>
	    <groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-log4j2</artifactId>
	</dependency>
	<!-- logging end -->

	<!-- http begin -->
	<dependency>
	    <groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpclient</artifactId>
    </dependency>
	<!-- http end -->

	<!-- fastjson begin -->
	<dependency>
	    <groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>1.2.46</version>
	</dependency>
	<!-- fastjson end -->

 

热部署

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
</dependency>

<build>
    <plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
			<configuration>
                <fork>true</fork>
            </configuration>
		</plugin>
	</plugins>
</build>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sky丶jarvan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值