公式:使用spring创建对象

这篇博客介绍了如何在Spring框架中通过XML配置文件来创建和管理对象。示例展示了如何定义bean并注入依赖,以及如何在Java测试类中使用ClassPathXmlApplicationContext获取对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

## 公式:使用spring创建对象

```
//创建一个实体类
```

```
//bean,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-bean.xsd">
    <bean id="mysqlImpl" class="com.kuang.dao.UserDaoMYSQL"/>
    <bean id="oracleImpl" class="com.kuang.dao.UserDaoORACLE"/>
    <bean id="userDaoImpl" class="com.kuang.dao.UserDaoImpl">
        <property name="userDao" ref="mysqlImpl"></property>
    </bean>
</beans>
```

```
//class MyTest
//在此使用CPXAC创建对象

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
        Hello hello=(Hello) context.getBean("Hello");
//        至此,已获得Hello类的对象hello
    }
```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值