spring总结(二)--helloworld

本文介绍如何在Java项目中使用Spring框架创建Bean实例。首先通过普通方式创建对象并调用方法,然后利用Spring容器进行Bean的定义与实例化,并展示了如何通过配置文件指定Bean属性。

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

一 创建一个普通的javaproject

    工程的目录结构如下:

    

二 不使用spring的情况

package com.lisx.spring.beans;

public class Main {

    public static void main(String[] args) {

        // new一个对象
        HelloWorld helloWorld = new HelloWorld();
        helloWorld.print();
    }
}

输出结果:

HelloWorld0

三 使用spring创建bean

    1:必须下载五个jar包才行

        

       a: commons-logging-1.1.1.jar我是到maven中央仓库中去下载的,下载地址为

         https://repo.maven.apache.org/maven2/commons-logging/commons-logging/1.1.1/

       b: 剩下4个jar包是到spring官网下载的

        http://projects.spring.io/spring-framework/

2:创建spring-bean1.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.lisx.spring.beans.HelloWorld">
        <property name="age" value="10000"></property>
    </bean>
</beans>

3:main.java

package com.lisx.spring.beans;

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

public class Main {

    public static void main(String[] args) {

        // 使用spring创建bean
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-bean1.xml");
        HelloWorld helloWorld1 = (HelloWorld) ctx.getBean("helloWorld");
        helloWorld1.print();
    }
}

4:输出结果

五月 13, 2018 11:28:49 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@230c34a9: startup date [Sun May 13 23:28:49 CST 2018]; root of context hierarchy
五月 13, 2018 11:28:49 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-bean1.xml]
HelloWorld10000

不仅输出结果,还输出了日志。并且在创建spring-bean1.xml文件时还修改了bean的值。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋天的猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值