自动装配
通过ByType
<?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:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 自动装配 byName 按照名字装配,要求bean的id于servcie中声明的对象一致 byType 按照类型装配,要求容器中该类型只能有一个实例 --> <bean id="userDAO4" class="cn.cqie.dao.impl.UserDAOImpl"></bean> <bean id="userService4" class="cn.cqie.service.impl.UserServiceImpl" autowire="byType"></bean> </beans>
@Test public void testAutowireByType(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("app5.xml"); UserServiceImpl userService4 = (UserServiceImpl) applicationContext.getBean("userService4"); userService4.save(); }
通过ByName
<?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:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 自动装配 byName 按照名字装配,要求bean的id于servcie中声明的对象一致 byType 按照类型装配,要求容器中该类型只能有一个实例 --> <bean id="userDAO" class="cn.cqie.dao.impl.UserDAOImpl"></bean> <bean id="userService4" class="cn.cqie.service.impl.UserServiceImpl" autowire="byName"></bean> </beans>
@Test public void testAutowireByName(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("app5.xml"); UserServiceImpl userService4 = (UserServiceImpl) applicationContext.getBean("userService4"); userService4.save(); }
FactoryBean
Spring 中有两种类型的Bean,一种是普通Bean,另一种是工厂Bean 即 FactoryBean。FactoryBean跟普通Bean不同,其返回的对象不是指定类的一个实例,而是该FactoryBean的getObject方法所返回的对象。创建出来的对象是否属于单例由isSingleton中的返回决定。
一般情况下,Spring通过反射机制利用的class属性指定实现类实例化Bean,在某些情况下,实例化Bean过程比较复杂,如果按照传统的方式,则需要在中提供大量的配置信息。配置方式的灵活性是受限的,这时采用编码的方式可能会得到一个简单的方案。Spring为此提供了一个org.springframework.bean.factory.FactoryBean的工厂类接口,用户可以通过实现该接口定制实例化Bean的逻辑。FactoryBean接口对于Spring框架来说占用重要的地位,Spring自身就提供了70多个FactoryBean的实现。它们隐藏了实例化一些复杂Bean的细节,给上层应用带来了便利。从Spring3.0开始,FactoryBean开始支持泛型,即接口声明改为FactoryBean的形式
以Bean结尾,表示它是一个Bean,不同于普通Bean的是:它是实现了FactoryBean接口的Bean,根据该Bean的ID从BeanFactory中获取的实际上是FactoryBean的getObject()返回的对象,而不是FactoryBean本身,如果要获取FactoryBean对象,请在id前面加一个&符号来获取。
<?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:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userService" class="cn.cqie.util.UserServiceFactoryBean"/> <!-- 这里的userService 是在cn.cqie.util.UserServiceFactoryBean 中的 getObject() 方法的返回值--> </beans>
package cn.cqie.util; import cn.cqie.dao.impl.UserDAOImpl; import cn.cqie.service.UserService; import cn.cqie.service.impl.UserServiceImpl; import org.springframework.beans.factory.FactoryBean; public class UserServiceFactoryBean implements FactoryBean<UserService> { /* 通过FactoryBean返回指定类型的对象 */ @Override public UserService getObject() throws Exception { //编写复杂的组装逻辑 UserServiceImpl userService = new UserServiceImpl(); userService.setUserDAO(new UserDAOImpl()); return userService; } @Override public Class<?> getObjectType() { //当前对象的类型 return null; } @Override public boolean isSingleton() { //返回的对象是否为单例 return false; } }
@Test public void testFactoryBean(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("app6.xml"); UserServiceImpl userService = (UserServiceImpl) applicationContext.getBean("userService"); userService.save(); }
Spring常用注解
可以通过注解可以在配置文件中少写一些内容
在配置文件中添加命名空间context,还需添加格式文件
xmlns:context="http://www.springframework.org/schema/context" 需要在xsi:schemaLocation中加入格式文件 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
@Component 这是下面三个的老大
@Controller
@Service 在service的类上加
@Repository 在 dao 层 mapper 层 加
注意:
1、需要注入的对象,在属性上添加注解@Autowire或者@Resource
2、所有bean的id默认为类名首字母小写。否则需要在注解中声明实例的id。
eg
MyBatis注解
mybatis的配置文件
<?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> <package name="cn.cqie.pojo"/> </typeAliases> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/springmybatis?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/> <property name="username" value="root"/> <property name="password" value="tcx119"/> </dataSource> </environment> </environments> <mappers> <!-- resource: xml所在的目录 读取本地磁盘的xml 要用 url(file:///D:1.xml) --> <mapper resource="cn/cqie/mapper/ad.xml"/> </mappers> </configuration>
写SQL语句的xml文件
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.cqie.mapper.UserMapper"> <select id="selectAll" resultType="User"> select <include refid="BASE_COL_LIST"></include> from user </select> <sql id="BASE_COL_LIST"> uname,pwd,hobby </sql> </mapper>
注解
注意:在使用注解时要重新关联
package cn.cqie.mapper; import cn.cqie.pojo.User; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper { @Select("select * from user") List<User> selectAll(); @Insert("insert into user values(#{uname},#{pwd},#{hobby})") int save(User user1); }
package cn.cqie.test; import cn.cqie.mapper.UserMapper; import cn.cqie.pojo.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.util.List; public class testApp { @Test public void testSelectAll() throws IOException { SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml")); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); //插入一条内容 User user = new User("yhl", "dasd", "ai"); int save = mapper.save(user); //这里一定要写,不然 在本地数据库中是没有的 sqlSession.commit(); List<User> users = mapper.selectAll(); System.out.println(users); } }
mybaties逆向工程
插件
时区: serverTimezone=Asia/Shanghai
特别注意
若mysql的版本在8以及以上 一定要写上时区
Spring与MyBatis集成
Spring+Mybatis
1、添加依赖
关于Mybatis依赖
关于Spring的依赖
关于Mybatis和Spring关联的依赖
其他依赖
<!-- mybatis --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.23</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.18.RELEASE</version> </dependency> <!-- 对于持久层框架的支持 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.18.RELEASE</version> </dependency> <!-- mybatis和Spring关联的jar --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
2、逆向生成Mybatis代码 or 手写
3、Spring的配置文件
<?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" 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"> <!--(扫描要被Spring管理的实例) 如果不想在xml文件中配置bean, 我们可以给我们的类加上spring组件注解,只需再配置下spring的扫描器就可以实现bean的自动载入。--> <context:component-scan base-package="cn.cqie"/> <!-- 生成数据库连接池对象--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="url" value="jdbc:mysql://localhost:3306/springmybatis?characterEncoding=utf8& serverTimezone=Asia/Shanghai"/> <property name="username" value="root"/> <property name="password" value="tcx119"/> </bean> <!-- 生成SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="typeAliasesPackage" value="cq.cqie.pojo"/> </bean> <!-- 扫描所有dao--> <!-- 通过下面的配置扫描cn.cqie.dao,将所有dao接口对应dao.xml生成对应的实例--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> <property name="basePackage" value="cn.cqie.dao"/> </bean> </beans>
4、生成代码
UserServiceImpl
package cn.cqie.service.impl; import cn.cqie.dao.UserDao; import cn.cqie.pojo.User; import cn.cqie.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class UserServiceImpl implements UserService { @Resource private UserDao userDao; @Override public List<User> findAll() { return userDao.selectByExample(null); } }
UserServlet
package cn.cqie.controller; import cn.cqie.pojo.User; import cn.cqie.service.impl.UserServiceImpl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/userServlet") public class UserServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("app.xml"); UserServiceImpl userServiceImpl = (UserServiceImpl) applicationContext.getBean("userServiceImpl"); List<User> all = userServiceImpl.findAll(); req.setAttribute("all",all); req.getRequestDispatcher("list.jsp").forward(req,resp); } }
list.jsp
<%-- Created by IntelliJ IDEA. User: admin Date: 2021/11/12 Time: 18:17 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>Title</title> </head> <body> <table> <c:forEach items="${requestScope.all}" var="all"> <tr> <td>${all.uname}</td> </tr> </c:forEach> </table> </body> </html>
以下需要注意
**若要使用@ WebServlet 注解 需要添加依赖**
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency>
**JSTL与EL需要导入的依赖**
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.el/javax.el-api --> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>3.0.1-b06</version> </dependency>