Spring的本结构
在src的根目录下有个bean.xml文件
关于xml文件是提示问题
可以这样的设置(在eclipse)
Window -> preferences->xml->xml catalog->add->在location的fileSYS
E:\hiberbate&Spring\spring\spring-beans-3.0.xsd
一个简单的Spring 如下:
在bean 文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 将PersonService类部署成Spring容器中的Bean -->
<bean id="personService" class="org.crazyit.app.service.PersonService">
<property name="name" value="wawa"/>
</bean>
</beans>
package org.crazyit.app.service;
public class PersonService
{
private String name;
//name属性的setter方法
public void setName(String name)
{
this.name = name;
}
//测试Person类的info方法
public void info()
{
System.out.println("此人名为:"
+ name);
}
在设置有参数的构造方法时;一定要有
public PersonService(){}
public PersonService(String name){}
}
package lee;
import org.crazyit.app.service.PersonService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest
{
public static void main(String[] args)
{
//创建Spring的ApplicationContext
ApplicationContext ctx = new ClassPathXmlApplicationContext
("bean.xml");
//输出Spring容器
System.out.println(ctx);
PersonService p = ctx.getBean("personService" , PersonService.class);
//p.setName("dsfaf");
p.info();
}
}
这一切都依赖Spring 容器
Spring容器根据配置文件信息,负责创建person实例
IOC(inversion of Control)
Di(dependency lnjection)
scope
The scope of this bean: typically "singleton" (one shared instance, which will be returned by
all calls to getBean with the given id), or "prototype" (independent instance resulting from
each call to getBean). By default, a bean will be a singleton, unless the bean has a parent
bean definition in which case it will inherit the parent's scope. Singletons are most commonly
used, and are ideal for multi-threaded service objects. Further scopes, such as "request" or
"session", might be supported by extended bean factories (e.g. in a web environment). Inner
bean definitions inherit the singleton status of their containing bean definition, unless
explicitly specified: The inner bean will be a singleton if the containing bean is a singleton,
and a prototype if the containing bean has any other scope.