spring配置文件(spring的开发步骤;bean中的scope,init-method,destroy-method;bean的工厂静态方法实例化;工厂动态方法实例化)
程序员文章站
2022-06-17 08:26:28
一、spring的开发步骤package com.lt.dao;public interface UserDao { void save();}package com.lt.dao.impl;import com.lt.dao.UserDao;public class UserDaoImpl implements UserDao { public void save() { System.out.println("save runing");...
一、spring的开发步骤
package com.lt.dao;
public interface UserDao {
void save();
}
package com.lt.dao.impl;
import com.lt.dao.UserDao;
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("save runing");
}
}
1、导入坐标 pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
</dependencies>
2、创建spring config文件(resources文件夹下),添加bean
<bean id="userDao" class="com.lt.dao.impl.UserDaoImpl"/>
3、调用
import com.lt.dao.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserDaoDemo {
public static void main(String[] args) {
ApplicationContext app =new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) app.getBean("userDao");
userDao.save();
}
}
二、bean中的scope,init-method,destroy-method
1、实现
package com.lt.dao.impl;
import com.lt.dao.UserDao;
public class UserDaoImpl implements UserDao {
public UserDaoImpl() {
System.out.println("UserDaoImpl创建");
}
public void save() {
System.out.println("save runing");
}
//方法名随便起
public void init(){
System.out.println("UserDaoImpl初始化");
}
public void destroy(){
System.out.println("UserDaoImpl 销毁");
}
}
2、配置
<!-- 方法一:无参构造方法实例化-->
<!--id=bean实例在spring容器里的唯一标识,
class=bean的全限定名,
scope=作用范围。默认单例singleton(加载配置文件时创建) 或多例 prototype(getBean()方法时创建)
init-method=初始化方法。
destroy-method=销毁方法
-->
<bean id="userDao" class="com.lt.dao.impl.UserDaoImpl" scope="singleton"
init-method="init" destroy-method="destroy"
/>
三、工厂静态方法实例化
package com.lt.factory;
import com.lt.dao.UserDao;
import com.lt.dao.impl.UserDaoImpl;
public class StaticFactory {
public static UserDao getUserDao(){
return new UserDaoImpl();
}
}
<!-- 方法二:工厂静态方法实例化-->
<bean id="userDao" class="com.lt.factory.StaticFactory"
factory-method="getUserDao"/>
四、工厂动态方法实例化
package com.lt.factory;
import com.lt.dao.UserDao;
import com.lt.dao.impl.UserDaoImpl;
public class DynamicFactory {
public UserDao getUserDao(){
return new UserDaoImpl();
}
}
<!-- 方法三:工厂动态方法实例化-->
<bean id="factory" class="com.lt.factory.DynamicFactory"/>
<bean id="userDao" factory-bean="factory" factory-method="getUserDao"/>
本文地址:https://blog.csdn.net/tiz198183/article/details/112291218