目录
????????定义Spring核心容器管理的对象。
<beans>
<bean/>
<bean></bean>
</beans>
示例:
<bean id="bookDao" class="com.spring.dao.impl.BookDaoImpl"/>
<bean id="bookService" class="com.spring.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"/>
</bean>
提供方法
public class BookDaoImpl implements BookDao {
public BookDaoImpl(){
System.out.println("111");
}
public void save(){
System.out.println("book dao save ...");
}
}
配置(类似中间容器,绑定关系)
<bean
id="bookDao"
class="com.spring.dao.impl.BookDaoImpl"/>
使用(先获取容器中的bean,再使用其方法)
public class APP2 {
public static void main(String[] args) {
//3.获取IoC容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//4.获取bean
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
}
}
静态工厂
public class OrderDaoFactory {
public static OrderDao getOrderDao(){
return new OrderDaoImpl();
}
}
配置
<bean
id="orderDao"
class="com.spring.factory.OrderDaoFactory"
factory-method="getOrderDao"/>
实例工厂
public class UserDaoFactory {
public UserDao getUserDao(){
return new UserDaoImpl();
}
}
配置
<bean id="userFactory" class="com.spring.factory.UserDaoFactory"/>
<bean id="userDao" factory-method="getUserDao" factory-bean="userFactory"/>
FactoryBean
public class UserDaoFactoryBean implements FactoryBean<UserDao> {
@Override
//代替原始实例工厂中创建对象的方法
public UserDao getObject() throws Exception {
return new UserDaoImpl();
}
@Override
public Class<?> getObjectType() {
return UserDao.class;
}
}
UserDaoImpl类
public class UserDaoImpl implements UserDao {
public void save(){
System.out.println("user dao save");
}
}
配置
<bean id="userDao" class="com.spring.factory.UserDaoFactoryBean"/>
使用
public class AppForInstanceUser {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) ctx.getBean("userDao");
userDao.save();
}
}