Spring入门bean.xml配置

1.导入Spring相关jar包

4个核心
在spring-framework-3.2.0.RELEASE-dist.zip中
1. spring-beans-3.2.0.RELEASE.jar
2. spring-context-3.2.0.RELEASE.jar
3. spring-core-3.2.0.RELEASE.jar
4. spring-expression-3.2.0.RELEASE.jar


两个日志
在spring-framework-3.0.2.RELEASE-dependencies.zip中
commons-logging日志整合,与slf4j类似,由apache提供
1. commons-logging-1.1.1.jar
2. log4j-1.2.15.jar

2.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">
    <!--Spring万能工厂-->
    <!-- UserDao userDao=new UserDaoImpl()-->
    <bean id="userDao" class="com.test.dao.UserDaoImpl></bean>
    <bean id="userService" class="com.test.service.UserServiceImpl">
        <!-- 让userService类中的属性userDao 指向id为userDao的Bean,即com.test.dao.UserDaoImpl-->
        <property name="userDao" ref="userDao"></property>
    </bean>

</bean>

//test
public static void main(String[] args)
{
    ApplicationContext appContext = new ClassPathXmlApplicationContext("application.xml");
    UserService userService = (UserService)appContext.getBean("userService");
    userService.method();//伪代码...
}

Springxml配置文件:

spring默认使用类的无参构造方法实例化对象
实例化对象:单例
scope:
singleton默认单例
prototype多例
spring容器中的Bean对象的生命周期:
1.默认情况下随着spring初始化的时候就实例化对象(new ClassPathXmlApplicationContext())
2. 调用init-method指定的初始化方法
3. 当spring容器销毁时调用destroy-method指定的方法完成销毁操作.

//init-method随着实例化对象时,调用该属性指定的方法init,用于初始化属性.
//destroy-method销毁对象时执行的资源回收操作-->ac.close();spring工厂关闭
<bean id="user" init-method="init" destroy-method="destroy" class="com.test.po.User">
<!--setter方法初始化属性(注入)-->
<property name="userId" value="12"></property>
<property name="username" value="张三"></property>
</bean>
<!--构造方法初始化的方式-->
<bean id = "user1" class="com.test.po.user1">
    <constructor-arg index="0" value="123" ></constructor-age>
    ...
    ...
</Bean>

p命名空间:applicationContext.xml文件头中引入
xmlns:p=”http://www.springframework.org/schema/p”

//简化setter注入
<bean id="dept1" class="com.test.po.dept">
    p:deptId="123"
    p:deptName="人事部"
</bean>

多个配置文件的引入

//在applicationContext.xml中使用import
<?xml...?>
<beans xmlns="..."
xmlns:xsi="..."
xmlns:p="..."
xsi:schemaLocation="...">
    <import resource="applicationContext-user.xml"/>
    <import resource="applicationContext-dept.xml"/>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值