首先创建一个项目
然后是项目名
下图:
创建完项目先配置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.csw.ssm</groupId> <artifactId>SpringBean</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.1.0.RELEASE</spring.version> </properties> <dependencies> <!-- Spring Web MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator --> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.13.Final</version> </dependency> <!-- servlet 系列的支持 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.7</version> </dependency> <!-- Springframework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.1</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <!-- 数据库驱动以及数据库连接池--> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!-- 日志框架 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.0</version> </dependency> <!-- 通用工具 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.7</version> </dependency> <!-- 单元测试 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>contact</finalName> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <dependencies> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>2.3.0</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
在resources下配MyBatis文件generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!--jdbc 驱动包,等--> <!--<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />--> <context id="sss" targetRuntime="MyBatis3Simple"> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <jdbcConnection driverClass="org.mariadb.jdbc.Driver" connectionURL="jdbc:mariadb://localhost/student" userId="root" password="13794709305"> </jdbcConnection> <javaModelGenerator targetPackage="com.csw.entity" targetProject="src\main\java"> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="mapper" targetProject="src\main\resources"> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.csw.dao" targetProject="src\main\java"> </javaClientGenerator> <table tableName="%"> <property name="useActualColumnNames" value="true"/> </table> </context> </generatorConfiguration>
配置jdbc.properties.xml
jdbc.driver=org.mariadb.jdbc.Driver jdbc.url=jdbc:mariadb://localhost:3306/student jdbc.user=root jdbc.password=13794709305 jdbc.txType=JDBC
配置日志文件logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern> %msg%n </Pattern> </layout> </appender> <logger name="com.csw.dao" level="debug" additivity="false"> <appender-ref ref="STDOUT" /> </logger> <root level="error"> <appender-ref ref="STDOUT" /> </root> </configuration>
配置mybatis-config.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> <settings> <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 --> <setting name="useGeneratedKeys" value="true" /> <!-- 使用列别名替换列名 默认:true --> <setting name="useColumnLabel" value="true" /> <!-- 开启驼峰命名转换:Table {create_time} -> Entity {createTime} --> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> <!--<!–定义一些可以复用的变量–>--> <!--<properties resource="jdbc.properties" />--> <!--<settings>--> <!--<setting name="cacheEnabled" value="true" /> <!– 开启二级缓存 –>--> <!--<setting name="autoMappingBehavior" value="PARTIAL"/>--> <!--<setting name="mapUnderscoreToCamelCase" value="true"/>--> <!--<setting name="localCacheScope" value="SESSION" />--> <!--</settings>--> <!--<!–设置别名,可以简化在 xml 中的完全限定名的使用–>--> <!--<typeAliases>--> <!--<package name="com.csw.entity" /> <!– 可以跟 @Alias 结合使用 –>--> <!--</typeAliases>--> <!--<environments default="prod">--> <!--<environment id="prod">--> <!--<transactionManager type="JDBC" />--> <!--<dataSource type="POOLED">--> <!--<property name="driver" value="${driver}"/>--> <!--<property name="url" value="${url}"/>--> <!--<property name="username" value="${username}"/>--> <!--<property name="password" value="${password}"/>--> <!--</dataSource>--> <!--</environment>--> <!--</environments>--> <!--<databaseIdProvider type="DB_VENDOR">--> <!--<property name="MySQL" value="mysql"/>--> <!--<property name="SQL Server" value="sqlserver"/>--> <!--<property name="DB2" value="db2"/>--> <!--<property name="Oracle" value="oracle" />--> <!--</databaseIdProvider>--> <!--<!–指定映射器–>--> <!--<!–<mappers>–>--> <!--<!–<mapper resource="mapper/xxx.xml" />–>--> <!--<!–</mappers>–>--> </configuration>
配置spring-web.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans " xmlns:mvc="http://www.springframework.org/schema/c" xmlns:contxt="http://www.springframework.org/schema/p"> <!--跨域的配置--> <mvc:cors> <mvc:mapping path="/xxx" allowed-origins="http://localhost:8080" allowed-methods="GET,POST" allowed-headers="Accept-Charset,Accept,Content-Type" allow-credentials="true" /> <mvc:mapping path="/yyy/*" allowed-origins="*" allowed-methods="*" allowed-headers="*"/> </mvc:cors> <!--<!–配置验证器–>--> <!--<bean id="myValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">--> <!--<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>--> <!--<property name="validationMessageSource" ref="messageSource"/>--> <!--</bean>--> <!--<!–国际化–>--> <!--<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">--> <!--<property name="basename" value="classpath:messagesxx"/>--> <!--<property name="defaultEncoding" value="GBK"/>--> <!--</bean>--> <!--<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">--> <!--<property name="defaultLocale"--> <!--value="zh"/> <!–当通过 Accept-Language 自动确定 Locale 的方式已经满足不了你,那么你需要试试注册一个 LocaleResolver 来制定 Locale 策略–>--> <!--</bean>--> <!--<!–启用注解扫描–>--> <contxt:component-scan base-package="com.csw.controller" /> <!--<!–启用mvc的常用注解–>--> <!--<mvc:annotation-driven validator="myValidator" conversion-service="conversionService">--> <!--<!–@ResponseBody 的 UTF-8 编码–>--> <!--<mvc:message-converters register-defaults="true">--> <!--<bean class="org.springframework.http.converter.StringHttpMessageConverter">--> <!--<constructor-arg value="GBK"/>--> <!--</bean>--> <!--<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">--> <!--<property name="objectMapper">--> <!--<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">--> <!--<property name="failOnEmptyBeans" value="false"/>--> <!--<property name="dateFormat">--> <!--<bean class="java.text.SimpleDateFormat">--> <!--<constructor-arg value="yyyy 年 MM 月 dd 日 " />--> <!--</bean>--> <!--</property>--> <!--</bean>--> <!--</property>--> <!--<property name="prettyPrint" value="true" />--> <!--<property name="jsonPrefix" value="data: " />--> <!--</bean>--> <!--</mvc:message-converters>--> <!--</mvc:annotation-driven>--> <!--将所有的静态资源交还 Servlet 处理--> <mvc:default-servlet-handler /> <!--<!–配置返回页面–>--> <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">--> <!--<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />--> <!--<property name="prefix" value="/WEB-INF/jsp/" />--> <!--<property name="suffix" value=".jsp" />--> <!--</bean>--> <!--<!–配置上传下载–>--> <!--<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver" />--> </beans>
然后在resources里面spring文件夹里配置两个文件
spring-dao.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--使用外部文件--> <context:property-placeholder location="classpath:jdbc.properties" /> <!--创建数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="org.mariadb.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mariadb://localhost:3306/student" /> <property name="user" value="root" /> <property name="password" value="13794709305" /> <property name="maxPoolSize" value="30" /> <property name="minPoolSize" value="10" /> <property name="autoCommitOnClose" value="false" /> <property name="checkoutTimeout" value="10000" /> <property name="acquireRetryAttempts" value="2" /> </bean> <!--配置 mybatis--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.csw.entity" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="mapperLocations" value="classpath:mapper/*.xml" /> </bean> <!--<!–配置类型转换规则–>--> <!--<bean name="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">--> <!--<property name="converters">--> <!--<set>--> <!--<bean class="com.csw.databinder.MyStringToDateConverter" />--> <!--</set>--> <!--</property>--> <!--<property name="formatters">--> <!--<set>--> <!--<bean class="com.csw.demo_formatter.PersonAnnotationFormatter" />--> <!--</set>--> <!--</property>--> <!--</bean>--> <!--自动注入 Mapper--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <property name="basePackage" value="com.csw.dao" /> </bean> <!--配置声明式事务管理--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven proxy-target-class="true" /> </beans>
spring-service.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:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--启用注解--> <context:component-scan base-package="com.csw.dao"/> <!-- 启用 aspectj 方式 AOP--> <aop:aspectj-autoproxy proxy-target-class="true" /> </beans>
呃,好吧,有点乱 = =,进入正题吧。。。
实体类Stu
package com.csw.entity; public class Stu { private Integer id; private String name; private String weixin; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getWeixin() { return weixin; } public void setWeixin(String weixin) { this.weixin = weixin == null ? null : weixin.trim(); } }
定义接口StuService
package com.csw.service; import com.csw.entity.Stu; import java.util.List; public interface StuService { List<Stu> getStu(); }
接口实现StuServiceImpl
package com.csw.service.Impl; import com.csw.dao.StuMapper; import com.csw.entity.Stu; import com.csw.service.StuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class StuServiceImpl implements StuService { @Autowired private StuMapper stuMapper; @Override public List<Stu> getStu() { return stuMapper.selectAll(); } }
然后是java方式配置Bean SpringConfig
package com.csw.spring.configuration; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import javax.sql.DataSource; import java.beans.PropertyVetoException; @Configuration //通过该注解表明是一个Spring的配置,相当于xml @ComponentScan("com.csw") //配置扫包 @PropertySource("classpath:jdbc.properties") public class SpringConfig { // @Value("${jdbc.driver}") // private String jdbcDriver; // // @Value("${jdbc.url}") // private String jdbcUrl; // // @Value("#{jdbc.username}") // private String jdbcUsername; // // @Value("#{jdbc.password}") // private String jdbcPassword; @Bean public DataSource dataSource() throws PropertyVetoException { ComboPooledDataSource source = new ComboPooledDataSource(); // source.setDriverClass(jdbcDriver); // source.setJdbcUrl(jdbcUrl); // source.setUser(jdbcUsername); // source.setPassword(jdbcPassword); source.setDriverClass("org.mariadb.jdbc.Driver"); source.setJdbcUrl("jdbc:mariadb://localhost:3306/student"); source.setUser("root"); source.setPassword("13794709305"); // source.setDriverClass("${jdbc.driver}"); // source.setJdbcUrl("${jdbc.url}"); // source.setUser("${jdbc.user}"); // source.setPassword("${jdbc.password}"); source.setMaxPoolSize(30); return source; } /*@Bean(name = "sqlSessionFactory") 如果不写就默认方法的名字*/ @Bean("sqlSessionFactory") public SqlSessionFactoryBean sqlSessionFactory() throws PropertyVetoException { SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean(); ClassPathResource resource = new ClassPathResource("mapper/StuMapper.xml"); sqlSessionFactory.setTypeAliasesPackage("com.csw.entity"); sqlSessionFactory.setMapperLocations(new Resource[]{resource}); sqlSessionFactory.setConfigLocation(new ClassPathResource("mybatis-config.xml")); sqlSessionFactory.setDataSource(this.dataSource()); return sqlSessionFactory; } @Bean public MapperScannerConfigurer getMapperScannerConfigurer() { MapperScannerConfigurer configurer = new MapperScannerConfigurer(); configurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); configurer.setBasePackage("com.csw.dao"); //扫描接口 return configurer; } }
最后是测试Main
package com.csw.test; import com.csw.entity.Stu; import com.csw.proxy.p1.Student; import com.csw.service.Impl.StuServiceImpl; import com.csw.service.StuService; import com.csw.spring.configuration.SpringConfig; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Stu_Main { public static void main(String[] args) { //通过java配置来实例化spring容器 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); //在spring容器中获取bean对象 StuService service = context.getBean(StuService.class); //Student student = (Student) service.getStu(); //调用对象中的方法直接循环遍历取出来 for (Stu stu : service.getStu()) { System.out.println("学号:" + stu.getId() + ",学生名字:" + stu.getName() + ",学生微信:" + stu.getWeixin()); } //销毁该容器 context.destroy(); } }
效果图如下:
原文地址:https://www.cnblogs.com/cheng88/p/10137036.html
时间: 2024-10-09 17:22:31