Spring入门helloworld的编写

Spring入门helloworld:

1.导包:

    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.2.1.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.2.1.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>5.2.1.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.1.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.1.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
  </dependency>

2.写配置:在Spring的核心配置文件中(applicaitonContext.xml)

    <!--注册一个Person对象,Spring会自动创建这个Person对象-->
    <!--一个Bean标签可以注册一个组件(对象、类) class:写要注册的组件的全类名
        id:这个对象的唯一标示
    -->
    <bean id="person" class="com.pojo.Person">
        <!--使用properties标签为Person对象的属性赋值
            name="lastName":指定属性名
            value="张三":为这个属性赋值
        -->
        <property name="lastName" value="张三"></property>
        <property name="age" value="20"></property>
        <property name="sex" value="男"></property>
    </bean>

3.测试:

    public void test1(){
        //ApplicationContext:代表ioc容器
        //ClassPathXmlApplicationContext:当前应用的xml配置文件在ClassPath下
        //根据spring的配置文件得到ioc容器对象
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println("ioc容器启动...");
        Person person = (Person) app.getBean("person");
        Object person1 = app.getBean("person");
        System.out.println(person==person1);
        System.out.println(person);
    }

注意这里存在的几个问题:

       1.src,源码包开始的路径,称为类路径的开始
        所有源码包里面的东西都会被合并放在类路径里面
            java:/bin/
            web:/WEB-INF/classes/
       2.导包commons-logging-1.1.3.jar(依赖)
       3.先导包在创建配置文件
       4.Spring的容器接管了标志了s的类

几个细节:

        1.ApplicationContext(IOC容器的接口)
        2.给容器中注册一个组件,我们也从容器中按照id拿到了这个组件的对象
            组件的创建工作,是容器完成
            Person对象是什么时候创建好了呢?
            容器中对象的创建在容器创建完成的时候就已经创建好了
        3.同一个组件在ioc容器是单例的;容器启动完成都已经创建准备好的
        4.容器中如果没有这个组件,获取组件?报异常:NoSuchBeanDefinitionException  No bean named 'person03' is defined
        5.ioc容器在创建这个组件对象的时候,(property)会利用setter方法为javaBean的属性进行赋值
        6.javaBean的属性名是由什么决定的?getter/setter方法是属性名;set去掉后面那一串首字母小写的值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值