Spring 练习1

    xiaoxiao2025-02-05  55

     

    参考: https://blog.csdn.net/feng_zhiyu/article/details/81149480

     

    项目轮廓

     

    1、使用MyEclipse10 创建Web project。

    2、选中项目,在MyEclipse10菜单栏的MyEclipse菜单下选择 Add Capabilities :添加 Spring Capalities。

    3、将Test.java做为java application运行。

     

     

    添加java类

     

    package com.spring.test; public class Person { private String name; private String context; public String getName() { return name; } public Person(String name, String context) { this.name = name; this.context = context; } public String getContext() { return context; } public void say() { System.out.println(name + " " + context); } }

     

    package com.spring.test; public class Show { private Person person; public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public void show() { person.say(); } }

     

    package com.spring.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Show show = (Show)context.getBean("show"); show.show(); Person person = new Person("Hello", "Spring"); Show show1 = new Show(); show1.setPerson(person); show1.show(); } }

     

    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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="person" class="com.spring.test.Person"> <constructor-arg value="Hello" /><!-- DI中的构造器注入 --> <constructor-arg value="Spring" /> <!-- value属性:Person类中setter方法中的参数对应的值 --> </bean> <!-- 下面这一句相当于 Show show = new Show(); --> <bean id="show" class="com.spring.test.Show"> <!-- 下面这一句相当于 show.setPerson(person); --> <property name="person" ref="person" /><!-- DI中的属性注入 --> <!-- ref属性 : 引用id为person的配置 --> </bean> </beans>

     

    log4j.properties

    log4j.rootLogger=WARN, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.File=target/spring.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

     

     

    最新回复(0)