Spring工程搭建

spring项目搭建一般步骤为
创建一各Java项目,新建lib文件夹,把jar导入配置xml文件

需要的jar包

一个基本的Spring需要的jar包一共五个
在这里插入图片描述

创建JavaBean类

Spring框架中bean指由Spring容器创建并管理的Java对象。不需要自己创建对象,Spring会把创建好的对象放在spring容器中,只需要从spring容器中取这些对象即可

public class User {
	private int age;
	private String name;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

配置xml文件

配置文件的命名可以是任意的,这里配置文件命名为applicationContext.xml

<?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="user" class="com.wl.spring.User">
		<property name="age" value="24" />
		<property name="name" value="张三"/>
	</bean>

</beans>

测试

通过Spring容器拿到对象

public class StartSpring {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		User user = (User) context.getBean("user");
		System.out.println(user.getAge());
		System.out.println(user.getName());
	}
}

结果

七月 08, 2019 8:41:00 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Mon Jul 08 20:41:00 CST 2019]; root of context hierarchy
七月 08, 2019 8:41:00 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
24
张三

注意:这里通过配置文件给创建的对象赋值其实就是调用了对象属性的setter方法。
例如 把setName()方法名改为setField()
再次运行测试代码将会报异常

七月 08, 2019 8:46:12 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Mon Jul 08 20:46:12 CST 2019]; root of context hierarchy
七月 08, 2019 8:46:12 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
七月 08, 2019 8:46:12 下午 org.springframework.context.support.ClassPathXmlApplicationContext refresh
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'user' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [com.wl.spring.User]: Bean property 'name' is not writable or has an invalid setter method. Did you mean 'age'?
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'user' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [com.wl.spring.User]: Bean property 'name' is not writable or has an invalid setter method. Did you mean 'age'?
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1568)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1276)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
	at com.wl.spring.StartSpring.main(StartSpring.java:7)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [com.wl.spring.User]: Bean property 'name' is not writable or has an invalid setter method. Did you mean 'age'?
	at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:243)
	at org.springframework.beans.AbstractNestablePropertyAccessor.processLocalProperty(AbstractNestablePropertyAccessor.java:437)
	at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:292)
	at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:280)
	at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:95)
	at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1564)
	... 13 more

异常中有一条重要的信息为

Exception in thread "main" 
org.springframework.beans.factory.BeanCreationException:
 Error creating bean with name 'user' defined in class path resource [applicationContext.xml]: 
 Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: 
 Invalid property 'name' of bean class [com.wl.spring.User]: 
 Bean property 'name' is not writable or has an invalid setter method. Did you mean 'age'?

没有找到name的setter方法
更改xml配置文件就可以得到user对象的属性

<?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="user" class="com.wl.spring.User">
		<property name="age" value="24" />
		<!--把name该成了field因为User中把setName()方法改为了setField方法-->
		<property name="field" value="张三"/>
	</bean>
</beans>

执行测试代码的结果

七月 08, 2019 8:52:58 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Mon Jul 08 20:52:58 CST 2019]; root of context hierarchy
七月 08, 2019 8:52:58 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
24
张三

执行过程分析

BeanFactory
BeanFactory是基础类型的IOC容器,是管理bean容器的根接口,并提供了完整的IOC服务支持
简单来说BeanFactory就是一个管理Bean的工厂,它主要负责初始化各种Bean、调用生命周期等方法
ApplicationContext
ApplicationContext被称为应用上下文,是BeanFactory接口的子接口,在其基础上提供了其他的附加功能,扩展了BeanFactory接口
ClassPathXmlApplicationContext
ClassPathXmlApplicationContext是ApplicationContext的实现类,也在其基础上加了许多附加功能
该类从类路径ClassPath中寻找指定的XML配置文件,找到并完成对象实例化工作
其构造器源码如下:

public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
    this(new String[] {configLocation}, true, null);
}

public ClassPathXmlApplicationContext(
        String[] configLocations, 
        boolean refresh, 
        @Nullable ApplicationContext parent) 
        throws BeansException {
    super(parent);
    // 加载项目中的Spring配置文件
    setConfigLocations(configLocations);
    if (refresh) {
        // 刷新容器
        refresh();
    }
}

构造器的作用:

1.调用setConfigLocations方法加载项目中的Spring配置文件
2.调用refresh方法刷新容器(bean的实例化就在这个方法中)

refresh方法源码如下:

public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        // 准备容器刷新
        prepareRefresh();
        // Tell the subclass to refresh the internal bean factory.
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
        // Prepare the bean factory for use in this context.
        // 准备bean工厂对象
        prepareBeanFactory(beanFactory);
        try {
            // Allows post-processing of the bean factory in context subclasses.
            // 加载配置文件中的所有bean标签
            postProcessBeanFactory(beanFactory);
            ......
            ......
            // Instantiate all remaining (non-lazy-init) singletons.
            // 完成此上下文的bean工厂初始化,初始化所有剩余的单例bean
            finishBeanFactoryInitialization(beanFactory);
            // Last step: publish corresponding event.
            // 完成容器刷新
            finishRefresh();
        } catch (BeansException ex) {
            ......
        } finally {
            ......
        }
    }
}

refresh方法的作用:

1.准备容器刷新
2.准备bean工厂对象
3.加载配置文件中的所有bean标签
4.完成bean工厂实例化
5.完成容器刷新

context.getBean()

context.getBean()方法是通过配置文件中声明的bean标签id属性获取容器内的实例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值