Spring基本配置(1)

这篇博客介绍了如何在Spring中进行基本配置,包括使用XML配置文件创建Bean以及采用注解方式进行配置。通过示例代码展示了HelloWorld类的定义,以及不同方式下获取和使用Bean的方法。

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

首先将Spring所需要的包导入:


首先是带xml的方式

spring.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="hw" class="com.yc.spring.HelloWorld" scope="prototype">

    </bean>

</beans>


HelloWorld.class:

package com.yc.spring;

import org.springframework.stereotype.Component;


public class HelloWorld {
    public HelloWorld(){
        System.out.println("helloworld的构造函数");
    }
    public void say(){
        System.out.println("helloworld spring");
    }
}


下面是使用注解方式:

package com.yc.spring;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//用这个类来代替xml文件

@Configuration
@ComponentScan("com.yc")
public class Appconfig {

}


HelloWorld.class:

package com.yc.spring;

import org.springframework.stereotype.Component;

@Component   //注解方式所需要的
public class HelloWorld {
    public HelloWorld(){
        System.out.println("helloworld的构造函数");
    }
    public void say(){
        System.out.println("helloworld spring");
    }
}


Test.class:

package spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.yc.spring.Appconfig;
import com.yc.spring.HelloWorld;

import junit.framework.TestCase;

public class Test extends TestCase {
        public void testApp(){//传统方式
            HelloWorld hw=new HelloWorld();
            hw.say();
        }
        
        public void testApp02(){//spring 控制反转方式
            //1读取sring.xml文件 创建spring容器(完成helloWorld对象的创建)
            ApplicationContext con=new ClassPathXmlApplicationContext("spring.xml");
            HelloWorld hw=(HelloWorld) con.getBean("hw");
            hw.say();
        }
        //注解方式
        public void testApp03(){//spring 控制反转方式
            //1读取sring.xml文件 创建spring容器(完成helloWorld对象的创建)
            ApplicationContext con=new AnnotationConfigApplicationContext(Appconfig.class);
            //HelloWorld hw=con.getBean(HelloWorld.class);//这样就产生了依赖,必须有HelloWorld这个类
            //hw.say();
            HelloWorld hw=(HelloWorld) con.getBean("helloWorld");//约定为类名第一个字母为小写   最前面的HelloWorld可面向接口  不产生依赖
            hw.say();
        
        }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值