无参构造
首先定义UserDao,UserDaoImpl,UserService,UserServiceImpl如下
public interface UserDao { } public class UserDaoImpl implements UserDao { } public interface UserService { void normalMethod(); } public class UserServiceImpl implements UserService, InitializingBean, DisposableBean { private UserDao userDao; public UserServiceImpl() { System.out.println("执行UserServiceImpl无参构造方法"); } public UserServiceImpl(String name) { System.out.println("执行UserServiceImpl有参构造方法, name = " + name); } public void setUserDao(UserDao userDao) { System.out.println("自动依赖注入,设置UserDao"); this.userDao = userDao; } @Override public void afterPropertiesSet() { System.out.println("执行InitializingBean的afterPropertiesSet"); } public void init() { System.out.println("执行bean标签定义的初始化方法"); } @Override public void normalMethod() { System.out.println("执行普通业务方法"); } @Override public void destroy() { System.out.println("执行DisposableBean的destroy"); } public void myDestroy() { System.out.println("执行bean标签定义的销毁方法"); } }
实例化UserDao的方式:
UserDao userDao = new UserDaoImpl();
以无参构造方法配置bean的方式:
<bean id="userDao" class="com.yt.dao.impl.UserDaoImpl"/>
验证
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserDao userDao = (UserDao) context.getBean("userDao"); System.out.println(userDao); // 输出 com.yt.dao.impl.UserDaoImpl@103f852 }
有参构造
实例化UserService的方式:
UserService userService = new UserServiceImpl("yt");
以有参构造方法配置bean的方式:
<bean id="userService" class="com.yt.service.impl.UserServiceImpl"> <constructor-arg name="name" value="yt"/> </bean>
验证
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println(context.getBean("userService")); // 输出 // 执行UserServiceImpl有参构造方法, name = yt // com.yt.service.impl.UserServiceImpl@179bb86 }
依赖注入
IOC控制反转,DI依赖注入,AOP面向切面编程是spring的三大特性。配置bean时想要自动注入bean的属性需要提供:bean要注入的对象对应的setter方法,被注入的bean,property标签。
<bean id="userService" class="com.yt.service.impl.UserServiceImpl"> <constructor-arg name="name" value="yt"/> <property name="userDao" ref="userDao"/> </bean> <bean id="userDao" class="com.yt.dao.impl.UserDaoImpl"/>
验证
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println(context.getBean("userService")); // 输出 // 执行UserServiceImpl有参构造方法, name = yt // 自动依赖注入,设置UserDao // com.yt.service.impl.UserServiceImpl@179bb86 }
bean标签的属性
<bean id="userService" name="aaa,bbb,ccc" // 别名,可起多个,getBean时可使用别名获取 class="com.yt.service.impl.UserServiceImpl" scope="prototype" // 默认单例singleton,非默认原型prototype,即每次获取bean都是不同的实例 lazy-init="true" //懒加载,只在获取bean时生成bean,默认非懒加载,启动容器就创建bean init-method="init" // 指定类里面的一个方法为初始化方法 destroy-method="myDestroy"> // 指定类里面的一个方法为销毁方法,需要手动关闭容器才可看到执行 </bean>
实现bean的初始化方法和销毁方法还有一种方式,实现InitializingBean, DisposableBean接口。bean标签指定的方法和实现接口的方法的执行顺序见运行结果
public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println(context.getBean("userService")); userService.normalMethod(); //当scope是prototype的时候,对象的生存周期spring就不管了。只有在tomcat或者容器关闭的时候,由tomcat调用 context.close(); } // 输出 // 执行UserServiceImpl无参构造方法 // 执行InitializingBean的afterPropertiesSet // 执行bean标签定义的初始化方法 // com.yt.service.impl.UserServiceImpl@179bb86 // 执行普通业务方法
静态工厂方法(字太多了,懒得写了)
<bean id="userService1" class="com.yt.factory.MyBeanFactory1" factory-method="getUserService"/>
实例工厂方法
<bean id="myBeanFactory2" class="com.yt.factory.MyBeanFactory2"/> <bean id="userService2" factory-bean="myBeanFactory2" factory-method="getUserService" lazy-init="true"/>
综合使用
记得导入坐标,再到mybaits官方文档的入门里面下一个xml配置文件模板,改成自己的,记得删掉mappe标签,因为没写
我还是贴出来
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/bai"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.23</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.23</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency>
当前版本为jdk8
<!--配置数据源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/bai"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!--配置Connection--> <bean id="clazz" class="java.lang.Class" factory-method="forName"> <constructor-arg name="className" value="com.mysql.jdbc.Driver"/> </bean> <bean id="connection" class="java.sql.DriverManager" factory-method="getConnection" scope="prototype"> <constructor-arg name="url" value="jdbc:mysql://localhost:3306/bai"/> <constructor-arg name="user" value="root"/> <constructor-arg name="password" value="123456"/> </bean> <!--配置一个当前时间--> <bean id="now" class="java.time.LocalDateTime" factory-method="now"/> <bean id="dateTimeFormatter" class="java.time.format.DateTimeFormatter" factory-method="ofPattern"> <constructor-arg name="pattern" value="yyyy-MM-dd HH:mm:ss"/> </bean> <bean id="nowString" factory-bean="now" factory-method="format"> <constructor-arg name="formatter" ref="dateTimeFormatter"/> </bean> <!--配置一个SqlSessionFactory--> <bean id="mybatisConfigInputStream" class="org.apache.ibatis.io.Resources" factory-method="getResourceAsStream"> <constructor-arg name="resource" value="mybatis-config.xml"/> </bean> <bean id="sqlSessionFactoryBuild" class="org.apache.ibatis.session.SqlSessionFactoryBuilder"/> <bean id="sqlSessionFactory" factory-bean="sqlSessionFactoryBuild" factory-method="build"> <constructor-arg name="inputStream" ref="mybatisConfigInputStream"/> </bean>
验证
public class ThirdPartyBeanTest { public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println(context.getBean("dataSource")); System.out.println(context.getBean("connection")); System.out.println(context.getBean("connection")); System.out.println(context.getBean("nowString")); InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlSessionFactory = builder.build(is); System.out.println(sqlSessionFactory); System.out.println(context.getBean("sqlSessionFactory")); } } // 输出 { CreateTime:"2022-11-10 23:53:05", ActiveCount:0, PoolingCount:0, CreateCount:0, DestroyCount:0, CloseCount:0, ConnectCount:0, Connections:[ ] } Thu Nov 10 23:53:05 CST 2022 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. com.mysql.jdbc.JDBC4Connection@1af006c Thu Nov 10 23:53:07 CST 2022 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. com.mysql.jdbc.JDBC4Connection@1d1433e 2022-11-10 23:53:05 org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@46293d org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@1997e9d Process finished with exit code 0
终于写完了,写个文章真难