java的Spring学习1--spring引用及属性(setter,getter)注入

1.目录结构

项目->src->main->java->com.test.ppmoney 设置java文件夹为代码  在Project Structure 里的 Modules里 选择相应的目录 后点击 Sources菜单

项目->src->main->resources 设置resources 文件夹为资源  在Project Structure 里的 Modules里 选择相应的目录 后点击 Resources菜单

2. 在依赖文件 pom.xml里添加 spring 依赖

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

3.在代码文件里添加相应的引用 

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

4.添加相应的bean文件

在resources文件下新建文件 如 bean1.xml

输入相应的代码如下:

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://www.springframework.org/schema/beans"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
             <bean id="teacher" class="com.test.com.Teacher">
         <property name="name" value="Yang"/>

     </bean>
 </beans>

5.主程序里输入以下代码

class Teacher extends  Observable
{
    public Teacher()
    {

    }
    public Teacher(String name)
    {
        this.name=name;
    }
    private String name;
    public void startLesson()
    {
        System.out.println(String.format("老师%s 开始上课",name));
        super.setChanged();
        super.notifyObservers();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

6.调用端代码如下:

ApplicationContext ctx = new ClassPathXmlApplicationContext("bean1.xml");//读取bean.xml中的内容

        Teacher sir=ctx.getBean("teacher",Teacher.class);
        if(sir==null)
        {
            System.out.println( "Teacher Init Failed..." );
        }
        else {
System.out.println( "Teacher Init Succ..." );
 }
原文地址:https://www.cnblogs.com/zhshlimi/p/6592826.html