Spring笔记(1)HelloWorld

本文介绍了一个使用Spring框架创建的简单Maven项目的示例。通过这个示例,读者可以了解到如何配置Spring容器来管理对象,并了解两种不同的依赖注入方式。

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

1.构建一个maven工程:
http://projects.spring.io/spring-framework/#quick-start

javapackage com.spring;

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

public class Day01 {



    public static void main(String[] args) {


        ApplicationContext  ctx=new ClassPathXmlApplicationContext("beans.xml");
     HelloWorld obj = (HelloWorld) ctx.getBean("helloworld");
     System.out.println(obj);
    }

}

beans.xml在src/main/resource中间。
beans.xml的头可以参照
http://docs.spring.io/spring/docs/4.2.0.BUILD-SNAPSHOT/spring-framewor...

其中http://docs.spring.io/spring/docs/
列举出了所有的版本的reference
beans.xml:

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="helloworld" class="com.spring.HelloWorld">
    <property name="age" value="12"></property>
    <property name="name" value="tango"></property>
    </bean>
</beans>

<property>中间,name应该指的是方法名,而不是属性名,因为反射是根据方法名来注入的。
还有一种注入方式,就是可以将字面值写到<value>标签中:

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="helloworld" class="com.spring.HelloWorld">
        <property name="age">
            <value>12</value>
        </property>
        <property name="name">
            <value>tango</value>            
        </property>
    </bean>
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值