Spring学习笔记1之IOC详解尽量使用注解以及java代码

网友投稿 201 2023-07-11


Spring学习笔记1之IOC详解尽量使用注解以及java代码

在实战中学习Spring,本系列的最终目的是完成一个实现用户注册登录功能的项目。

预想的基本流程如下:

1、用户网站注册,填写用户名、密码、email、手机号信息,后台存入数据库后返回ok。(学习IOC,mybatis,SpringMVC的基础知识,表单数据验证,文件上传等)

2、服务器异步发送邮件给注册用户。(学习消息队列)

3、用户登录。(学习缓存、Spring Security)

4、其他。

边学习边总结,不定时更新。项目环境为Intellij + Spring4。

一、准备工作。

1、mysql中建库建表。

2、Intellij中创建maven webapp工程。

(1) pom.xml中导入需要的依赖包。

xmlns:xsi="http://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">

4.0.0

com.everSeeker

register

war

1.0

register Maven Webapp

http://maven.apache.org

4.3.1.RELEASE

org.springframework

spring-context

${spring.version}

org.springframework

spring-context-support

${spring.version}

org.springframework

spring-core

${spring.version}

org.springframework

spring-beans

${spring.version}

junit

junit

4.12

org.springframework

spring-test

${spring.version}

org.springframework

spring-webmvc

${spring.version}

org.springframework

spring-web

${spring.version}

javax.validation

validation-api

1.1.0.Final

org.hibernate

hibernate-validator

5.2.4.Final

javax.servlet

javax.servlet-api

3.1.0

javax.servlet

jstl

1.2

org.springframework

spring-jdbc

${spring.version}

mysql

mysql-connector-java

6.0.3

org.mybatis

mybatis

3.4.1

org.mybatis

mybatis-spring

1.3.0

c3p0

c3p0

0.9.1.2

java_config_web

org.apache.maven.plugins

maven-war-plugin

2.2

false

xmlns:xsi="http://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">

4.0.0

com.everSeeker

register

war

1.0

register Maven Webapp

http://maven.apache.org

4.3.1.RELEASE

org.springframework

spring-context

${spring.version}

org.springframework

spring-context-support

${spring.version}

org.springframework

spring-core

${spring.version}

org.springframework

spring-beans

${spring.version}

junit

junit

4.12

org.springframework

spring-test

${spring.version}

org.springframework

spring-webmvc

${spring.version}

org.springframework

spring-web

${spring.version}

javax.validation

validation-api

1.1.0.Final

org.hibernate

hibernate-validator

5.2.4.Final

javax.servlet

javax.servlet-api

3.1.0

javax.servlet

jstl

1.2

org.springframework

spring-jdbc

${spring.version}

mysql

mysql-connector-java

6.0.3

org.mybatis

mybatis

3.4.1

org.mybatis

mybatis-spring

1.3.0

c3p0

c3p0

0.9.1.2

java_config_web

org.apache.maven.plugins

maven-war-plugin

2.2

false

(2) 工程目录结构如下所示:

二、Mybatis

1、配置mysql数据库的基本信息。

# Database

db.mysql.driverClass = com.mysql.jdbc.Driver

db.mysql.jdbcUrl = jdbc:mysql://localhost:3306/register_notice?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true

db.mysql.user = root

db.mysql.password = 333

db.minPoolSize = 10

db.maxPoolSize = 100

db.initialPoolSize = 20

db.maxIdleTime = 60

db.acquireIncrement = 5

db.maxStatements = 100

db.idleConnectionTestPeriod = 60

db.acquireRetryAttempts = 30

db.breakAfterAcquireFailure = true

db.testConnectionOnCheckout = false

db.properties

2、配置mybatis.xml以及spring-mybatis.xml。

PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

mybatis.xml

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xmlns:tx="http://springframework.org/schema/tx"

xmlns:p="http://springframework.org/schema/p"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx.xsd">

destroy-method="close">

p:dataSource-ref="dataSource"

p:configLocation="classpath:mybatis.xml"

p:mapperLocations="classpath*:mapper/*Mapper.xml" />

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

proxy-target-class="true" />

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xmlns:tx="http://springframework.org/schema/tx"

xmlns:p="http://springframework.org/schema/p"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx.xsd">

destroy-method="close">

destroy-method="close">

p:dataSource-ref="dataSource"

p:configLocation="classpath:mybatis.xml"

p:mapperLocations="classpath*:mapper/*Mapper.xml" />

p:dataSource-ref="dataSource"

p:configLocation="classpath:mybatis.xml"

p:mapperLocations="classpath*:mapper/*Mapper.xml" />

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

proxy-target-class="true" />

proxy-target-class="true" />

spring-mybatis.xml

3、创建User类以及UserDao接口。

public class User {

@Size(min = 32, max = 32, message = "uuid应该为32位字符串")

private String id;

@Size(min = 1, max = 32, message = "账号长度应该在1-32位之间")

private String username;

@NotEmpty(message = "密码不能为空")

private String password;

@NotEmpty(message = "email不能为空")

@Email(message = "email格式不正确")

private String email;

@Size(min = 11, max = 11, message = "手机号长度为11位")

private String cellphone;

private long regDate;

public User() {

this.id = UUID.randomUUID().toString().replaceAll("-", "");

this.regDate = 0;

}

public User(String username, String password, String email, String cellphone) {

this(username, password, email, cellphone, new Date().getTime());

}

public User(String username, String password, String email, String cellphone, long regDate) {

this.id = UUID.randomUUID().toString().replaceAll("-", "");

this.username = username;

this.password = password;

this.email = email;

this.cellphone = cellphone;

this.regDate = regDate;

}

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getCellphone() {

return cellphone;

}

public void setCellphone(String cellphone) {

this.cellphone = cellphone;

}

public long getRegDate() {

return regDate;

}

public void setRegDate(long regDate) {

this.regDate = regDate;

}

@Override

public String toString() {

return "[User: id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + ", cellphone=" +

cellphone + ", regDate=" + regDate + "]";

}

}

User.java

User.java中的@NotNull, @NotEmpty, @Size以及@Email等注释暂时忽略,以后解释。

@Repository

public interface UserDao {

void addUser(User user);

User getUserByUsername(String username);

}

4、在src/main/resources/mapper目录下创建UserMapper.xml映射文件,实现UserDao接口中的方法。注:*Mapper.xml文件必须放在src/main/resources目录下,之前放在src/main/java/com/everSeeker/dao目录下,产生了莫名奇妙的错误。

INSERT INTO user(id, username, password, email, cellphone, regDate) VALUES(#{id}, #{username}, #{password}, #{email}, #{cellphone}, #{regDate})

SELECT * FROM user WHERE username=#{username}

UserMapper.xml

三、IOC

1、创建IOC容器,通过注解方式,RootConfig.java。

@Configuration

@ComponentScan(basePackages = {"com.everSeeker"}, excludeFilters = {

@ComponentScan.Filter(type = FilterType.CUSTOM, value = RootConfig.WebPackage.class)})

@ImportResource({"classpath:spring-mybatis.xml"})

public class RootConfig {

public static class WebPackage extends RegexPatternTypeFilter {

public WebPackage() {

super(Pattern.compile("com\\.everSeeker\\.web"));

}

}

}

@Configuration: 表明这是一个配置类。

@ComponentScan: 启用组建扫描,basePackages:需要扫描的基础package。excludeFilters: 符合filter条件的不扫描。

@ImportResource: 引入xml文件。

@PropertySource: 引入properties文件。

2、由于创建的是webapp项目,并且采用了SpringMVC,那么DispatcherServlet是核心。以前的Spring版本中,一般会配置在web.xml中。而在Spring4中,可以在Java代码中来实现。WebAppInitializer.java。

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { //继承了AbstractAnnotationConfigDispatcherServletInitializer的类会自动配置DispatcherServlet和Spring应用上下文

@Override

protected String[] getServletMappings() { //将DispatcherServlet映射到"/"

return new String[] { "/" };

}

/**

* RootConfig类用来配置ContextLoaderListener创建的应用上下文中的bean,

* 比如@Repository, @Service等组件

*/

@Override

protected Class>[] getRootConfigClasses() {

return new Class>[] { RootConfig.class };

}

/**

* DispatcherServlet加载应用上下文时,使用定义在WebConfig配置类中的bean,

* 用来加载包含Web组件的bean,比如控制器,视图解析器以及处理器映射, @Controller, @RequestMapping等

*/

@Override

protected Class>[] getServletConfigClasses() {

return new Class>[] { WebConfig.class };

}

@Override

protected void customizeRegistration(ServletRegistration.Dynamic registration) {

//限制上传文件的大小不超过2MB,整个请求不超过4M,所有上传的文件都要写到磁盘中

registration.setMultipartConfig(new MultipartConfigElement("/tmp/uploads", 2097152, 4194304, 0));

}

}

3、创建WebConfig.java。

@Configuration

@EnableWebMvc

@ComponentScan("com.everSeeker.web")

public class WebConfig extends WebMvcConfigurerAdapter {

//配置jsp视图解析器

@Bean

public ViewResolver viewResolver() {

InternalResourceViewResolver resourceViewResolver = new InternalResourceViewResolver();

resourceViewResolver.setPrefix("/WEB-INF/views/");

resourceViewResolver.setSuffix(".jsp");

resourceViewResolver.setExposeContextBeansAsAttributes(true);

return resourceViewResolver;

}

//配置multipart解析器, 上传文件用

@Bean

public MultipartResolver multipartResolver() throws IOException {

return new StandardServletMultipartResolver();

}

//配置静态资源的处理

@Override

public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {

configurer.enable();

}

}

@Bean: 声明这个方法会创建所需类型的实例,并注册为Spring应用上下文中的bean。

以上所述是给大家介绍的Spring学习笔记1之IOC详解尽量使用注解以及java代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:spring mybatis多数据源实例详解
下一篇:java实现的AES加密算法完整实例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~