zoukankan      html  css  js  c++  java
  • 01-spring_helloworld

    demo结构

    代码:

    HelloWorld.java

    package com.demo.beans;
    
    public class HelloWorld {
    	private String name;
    	public void setName(String name) {
    		System.out.println("setName= "+name);
    		this.name = name;
    	}
    	public void hello(){
    		System.out.println("hello "+name);
    	}
    	
    	public HelloWorld() {
    		System.out.println("HelloWorld's Constructor");
    	}
    }
    

    Main.java

    package com.demo.beans;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Main {
    
    	public static void main(String[] args) {
    		/*
    		//创建helloworld的一个对象
    		HelloWorld helloWorld = new HelloWorld();
    		//为name属性赋值
    		helloWorld.setName("atguigu");
    		*/
    		//以上两步可以交给spring来完成
    		
    		//1.创建spring的IOC容器对象
    		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    		//2.从IOC容器中获取bean实例
    		HelloWorld helloWorld = (HelloWorld) context.getBean("helloworld");
    		//3.调用hello方法
    		//调用hello方法
    		//helloWorld.hello();
    	}
    

    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 -->
    	<bean id="helloworld" class="com.demo.beans.HelloWorld">
    		<property name="name" value="Spring"></property>
    	</bean>
    
    </beans>
    

    说明:

    1、使用spring的三部:创建springIOC容器对象,从容器中获取bean实例,调用相应的方法

    2、去掉1中的第3步,会发现,创建SpringIOC容器的时候,会帮我们初始化好bean实例并且将属性赋好值。

  • 相关阅读:
    LibreOJ #507. 「LibreOJ NOI Round #1」接竹竿
    BZOJ 4590: [Shoi2015]自动刷题机
    luogu P3808 【模板】AC自动机(简单版)
    cogs 2569. [東方] 博丽灵梦 梦想妙珠
    codeforces 1C. Ancient Berland Circus
    BZOJ 4570: [Scoi2016]妖怪
    HDU 1392 Surround the Trees
    cogs 999. [東方S2]雾雨魔理沙
    Uva 10652 Board Wrapping
    AC日记——[Sdoi2008]Cave 洞穴勘测 bzoj 2049
  • 原文地址:https://www.cnblogs.com/boucher/p/5737973.html
Copyright © 2011-2022 走看看