热门IT资讯网

spring IoC编程实例

发表于:2024-11-26 作者:热门IT资讯网编辑
编辑最后更新 2024年11月26日,配置文件/SpringHelloWorld/src/applicationContext.xml代码Welcome!

配置文件

/SpringHelloWorld/src/applicationContext.xml

  1. 代码
  2. xml version="1.0" encoding="UTF-8"?>
  3. <beans
  4. xmlns="http://www.springframework.org/schema/beans"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
  7. <bean id="greetingService" class="com.qdu.sun.spring.HelloWorld">
  8. <constructor-arg>
  9. <value type="java.lang.String">Welcome!value>
  10. constructor-arg>
  11. bean>beans>

SpringTest.java

  1. 代码
  2. package com.qdu.sun.spring;
  3. import org.springframework.beans.factory.BeanFactory;
  4. import org.springframework.beans.factory.xml.XmlBeanFactory;
  5. import org.springframework.core.io.ClassPathResource;
  6. public class SpringTest {
  7. public static void main( String[] args ){
  8. BeanFactory factory = new XmlBeanFactory( new ClassPathResource("applicationContext.xml") );
  9. HelloWorld gc = (HelloWorld)factory.getBean("greetingService");
  10. gc.sayGreeting();
  11. }
  12. }

HelloWorld.java

  1. 代码
  2. package com.qdu.sun.spring;
  3. public class HelloWorld {
  4. private String greeting;
  5. public HelloWorld(){
  6. }
  7. public HelloWorld( String greeting ){
  8. this.greeting = greeting;
  9. }
  10. public void sayGreeting(){
  11. System.out.println( greeting );
  12. }
  13. public void setGreeting( String greeting ){
  14. this.greeting = greeting;
  15. }
  16. }
0