Spring進修筆記1之IOC詳解盡可能應用注解和java代碼。本站提示廣大學習愛好者:(Spring進修筆記1之IOC詳解盡可能應用注解和java代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是Spring進修筆記1之IOC詳解盡可能應用注解和java代碼正文
在實戰中進修Spring,本系列的終究目標是完成一個完成用戶注冊登錄功效的項目。
料想的根本流程以下:
1、用戶網站注冊,填寫用戶名、暗碼、email、手機號信息,後台存入數據庫後前往ok。(進修IOC,mybatis,SpringMVC的基本常識,表雙數據驗證,文件上傳等)
2、辦事器異步發送郵件給注冊用戶。(進修新聞隊列)
3、用戶登錄。(進修緩存、Spring Security)
4、其他。
邊進修邊總結,不准時更新。項目情況為Intellij + Spring4。
1、預備任務。
1、mysql中建庫建表。
2、Intellij中創立maven webapp工程。
(1) pom.xml中導入須要的依附包。
<?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.everSeeker</groupId> <artifactId>register</artifactId> <packaging>war</packaging> <version>1.0</version> <name>register Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.3.1.RELEASE</spring.version> </properties> <dependencies> <!--spring core, context--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <!--test--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <!--<scope>test</scope>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!--springmvc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency> <!--servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--mysql, mybatis--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.3</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> </dependencies> <build> <finalName>java_config_web</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.2</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
(2) 工程目次構造以下所示:
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。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--設置裝備擺設實體類的別號--> <typeAliases> <!--以下2種辦法選其一便可。 第1種辦法:應用typeAlias,為單個類設置別號。--> <!--<typeAlias type="com.everSeeker.entity.User" alias="User" />--> <!--第2種辦法:應用package,為包上面的一切類設置別號,默許規矩為com.everSeeker.entity.User設置為User,去除後面的包名。--> <package name="com.everSeeker.entity" /> </typeAliases> </configuration> mybatis.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 在該文件中引入db.properties文件,可以包管以後的設置裝備擺設好比${db.mysql.driverClass}確定能找到對應的值 --> <!-- 不然,假如直接在RootConfig.java中同事載入db.properties和spring-mybatis.xml的話,不克不及包管db.properties先被引入,從而招致法式報錯 --> <context:property-placeholder location="classpath:db.properties"/> <!--數據源設置裝備擺設 c3p0 罕見的數據源完成類包有2個,一個是apache的DBCP(org.apache.commons.dbcp.BasicDataSource),另外一個為C3P0。 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${db.mysql.driverClass}" /> <property name="jdbcUrl" value="${db.mysql.jdbcUrl}" /> <property name="user" value="${db.mysql.user}" /> <property name="password" value="${db.mysql.password}" /> <!--銜接池中保存的最小銜接數。 --> <property name="minPoolSize" value="${db.minPoolSize}" /> <!--銜接池中保存的最年夜銜接數。Default: 15 --> <property name="maxPoolSize" value="${db.maxPoolSize}" /> <!--初始化時獲得的銜接數,取值應在minPoolSize與maxPoolSize之間。Default: 3 --> <property name="initialPoolSize" value="${db.initialPoolSize}" /> <!--最年夜余暇時光,60秒內未應用則銜接被拋棄。若為0則永不拋棄。Default: 0 --> <property name="maxIdleTime" value="${db.maxIdleTime}" /> <!--當銜接池中的銜接耗盡的時刻c3p0一次同時獲得的銜接數。Default: 3 --> <property name="acquireIncrement" value="${db.acquireIncrement}" /> <!--JDBC的尺度參數,用以掌握數據源內加載的PreparedStatements數目。但因為預緩存的statements 屬於單個connection而不是全部銜接池。所以設置這個參數須要斟酌到多方面的身分。 假如maxStatements與maxStatementsPerConnection均為0,則緩存被封閉。Default: 0 --> <property name="maxStatements" value="${db.maxStatements}" /> <!--每60秒檢討一切銜接池中的余暇銜接。Default: 0 --> <property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}" /> <!--界說在從數據庫獲得新銜接掉敗後反復測驗考試的次數。Default: 30 --> <property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}" /> <!--獲得銜接掉敗將會惹起一切期待銜接池來獲得銜接的線程拋出異常。然則數據源仍有用 保存,並鄙人次挪用getConnection()的時刻持續測驗考試獲得銜接。假如設為true,那末在測驗考試 獲得銜接掉敗後該數據源將聲名已斷開並永遠封閉。Default: false --> <property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}" /> <!--因機能消費年夜請只在須要的時刻應用它。假如設為true那末在每一個connection提交的 時刻都將校驗其有用性。建議應用idleConnectionTestPeriod或automaticTestTable 等辦法來晉升銜接測試的機能。Default: false --> <property name="testConnectionOnCheckout" value="${db.testConnectionOnCheckout}" /> </bean> <!-- myBatis設置裝備擺設. classpath和classpath*的差別,參考文檔:http://blog.csdn.net/zl3450341/article/details/9306983. classpath只會前往第一個婚配的資本,建議肯定途徑的單個文檔應用classpath;婚配多個文檔時應用classpath*. --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis.xml" p:mapperLocations="classpath*:mapper/*Mapper.xml" /> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--basePackage指定要掃描的包,在此包之下的映照器都邑被搜刮到。可指定多個包,包與包之間用逗號或分號分隔 MapperScannerConfigurer將掃描basePackage所指定包下的一切接口類(包含子包),假如他們在SQL映照文件 中界說過,則將他們靜態界說為一個Spring Bean. --> <property name="basePackage" value="com.everSeeker.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 事務治理器設置裝備擺設, 應用jdbc事務 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 應用annotation界說事務,對標注了@Transactional注解的bean停止處置,以織入事務治理切面. 默許情形下,主動應用稱號為transactionManager的事務治理器。 proxy-target-class為true,表現spring將經由過程創立子類來署理營業類,須要在類途徑中添加CGLib.jar類庫。--> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> </beans> 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目次下,發生了莫名奧妙的毛病。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.everSeeker.dao.UserDao"> <resultMap id="ResultMapUser" type="com.everSeeker.entity.User"> </resultMap> <insert id="addUser" parameterType="User"> INSERT INTO user(id, username, password, email, cellphone, regDate) VALUES(#{id}, #{username}, #{password}, #{email}, #{cellphone}, #{regDate}) </insert> <select id="getUserByUsername" parameterType="String" resultMap="ResultMapUser"> SELECT * FROM user WHERE username=#{username} </select> </mapper> UserMapper.xml
3、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代碼,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!