Educoder-Spring入门解答

2023-11-06

第一关:hello Spring

HelloWorld

package step1;
public class HelloWorld {
        /**********   Begin   **********/
        public void hello(){
            System.out.println("Hello Spring");
        }
        /**********   End   **********/
}

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">
    <bean id="helloworld" class="step1.HelloWorld"></bean>
</beans>

Test1

package step1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import step1.HelloWorld;
public class Test1 {
    public static void main(String[] args) {
        /********** Begin **********/
        //1、创建Spring的IOC容器的对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2、从IOC的容器中获取Bean的实例
        HelloWorld helloWorld = (HelloWorld) applicationContext.getBean("helloworld");
        //3、调用方法
        helloWorld.hello();
        /********** End **********/
    }
}

第二关:Spring IOC容器

package step2;

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

public class MainApp {
	public static void fun() {
    /********** Begin **********/
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext2.xml");
    boolean student = applicationContext.containsBean("student");
    boolean helloworld = applicationContext.containsBean("helloworld");
    Object bean = applicationContext.getBean("helloworld");
    HelloWorld bean2 = applicationContext.getBean(HelloWorld.class);
    HelloWorld bean3 = applicationContext.getBean("helloworld",HelloWorld.class);
    System.out.println(student+"\n"+helloworld+"\n"+bean.toString()+"\n"+bean2.toString()+"\n"+bean3.toString());
    /********** End **********/

	}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Educoder-Spring入门解答 的相关文章

随机推荐