Spring-helloworld

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40745306/article/details/88812011

先定义一个类

public class HelloWorld {
    private String name;
    public HelloWorld(){
        System.out.println("先调用无参构造器");
    }
    public void setName(String name) {
        this.name = name;
    }
    public void hello(){
        System.out.println("hello: "+name);
    }

普通方法使用
 public static void main(String[] args) {
        HelloWorld hello=new HelloWorld();
        hello.setName("张无忌");
        hello.hello();    
       }

使用Spring方法,先创建一个applicationContext.xml,配置Bean
    <!-- 配置Bean -->
    <bean id="helloWorld"  class="com.atguigu.beans.HelloWorld">
    <property name="name" value="Spring"></property>
    </bean>


再使用
     public static void main(String[] args) {
        //初始化Spring的IOC容器,加载配置文件(这一步会调用无参构造器、并给setter方法赋值)
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        //从IOC容器中获取实例
        HelloWorld hello=(HelloWorld)ctx.getBean("helloWorld");
        hello.hello();
    }

猜你喜欢

转载自blog.csdn.net/weixin_40745306/article/details/88812011