spring学习记录(持续更新)

mac2024-03-20  28

Spring

IOC

控制反转 xml中

<bean id="peopleServiceId" class="com.gqc.test02.PeopleServiceImpl"/>

DI

property: name :bean的属性名,通过set方法获得 setPeopleDao ##> PeopleDao ##> bookDao ref:另一个bean的id值的引用

<bean id="peopleServiceId" class="com.gqc.test02.PeopleServiceImpl"> <property name="peopleDao" ref="peopleDaoId"></property> </bean> <bean id="peopleDaoId" class="com.gqc.test02.PeopleDaoImpl"></bean> </beans>

spring的实例化的三种方式: 默认构造:如果类不是默认的空白构造那么通过xml配置的bean(id,class)是不能用的 静态工厂:通过创建自己的静态工厂MyBeanFactory中创建静态方法

public class MyBeanFactory { public static PeopleService createService() { return new PeopleServiceImpl(); } }

调用时直接通过静态方法

@Test public void test04() { PeopleService peopleService= MyBeanFactory.createService(); peopleService.add(); }

测试spring-bean

src/main/java com.gqc.test TestMain.java

package com.gqc.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestMain { //ApplicationContext applicationContext = // new ClassPathXmlApplicationContext("classpath*:applicationContext.xml"); public static void main(String[] args) { ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); userDao userDao=applicationContext.getBean("userDao",userDao.class); userDao.say(); } }

applicationContext.xml

写在src/main/resources里面

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 在这里加入内容 --> <bean id="userDao" class="com.gqc.test.userDao" /> </beans>
最新回复(0)