spring属性和构造器注入

搭建环境同上

  

1---在src/resource下加入-----applicationContext-web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
     <!--类构造器实例化-->
	<bean id="formaterBean" class="com.neusoft.test.spring.impl.UpperFormat" >
	</bean>
	<!--属性注入-->
    <bean id="textPrinter" class="com.neusoft.test.spring.impl.TextPrinter">
		<constructor-arg index="0">
			<ref bean="formaterBean"/>
		</constructor-arg>
		<constructor-arg index="1" value="Test constructor" />
	</bean>
</beans>

2---在src/java下加入

      三个包   format    impl   main

    1------- 在format中加入  -----Format.java   

package com.neusoft.test.spring.format;
public interface Foramt
{
  String format(String text);
}

    2------在impl中加入  -------

             (1)LowerFormat.java

package com.neusoft.test.spring.impl;
import com.neusoft.test.spring.format.Foramt;
public class LowerFormat implements Foramt
{
  public String format(String text) 
{
    return text.toLowerCase();
}
}

            (2)TextPrinter.java

package com.neusoft.test.spring.impl;

import com.neusoft.test.spring.format.Foramt;

public class TextPrinter
{
    private Foramt format;

    private String textString;
    
    public TextPrinter(Foramt format, String textString)
    {
        this.format = format;
        this.textString = textString;
    }

    public Foramt getFormat()
    {
        return format;
    }

    public void setFormat(Foramt format)
    {
        this.format = format;
    }

    public String getTextString()
    {
        return textString;
    }

    public void setTextString(String textString)
    {
        this.textString = textString;
    }
    public void print()
    {
        System.out.println(this.format.format(textString));
    }
}

        (3)UpperFormat.java

package com.neusoft.test.spring.impl;
import com.neusoft.test.spring.format.Foramt;
public class UpperFormat implements Foramt
{
    public String format(String text) 
    {
        return text.toUpperCase();
    }
}

3------- 在main中加入  -----Test.java

package com.neusoft.test.spring.main;


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

import com.neusoft.test.spring.impl.TextPrinter;
public class Test
{
    public static void main(String[] args)
    {
     //构造方法
     ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String("applicationContext-web.xml"));
     TextPrinter textPrinter = (TextPrinter)applicationContext.getBean("textPrinter"); 
     textPrinter.print();
    }
}


   

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页