spring + maven 属性注入和构造函数注入(1)

来源:互联网 发布:mac如何使用搜狗 编辑:程序博客网 时间:2024/05/29 04:33

1、新建maven项目;

2、pom 添加依赖:

  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>    <!-- Spring framework --><dependency><groupId>org.springframework</groupId><artifactId>spring</artifactId><version>2.5.6</version></dependency>  </dependencies>

3、新建一个bean类:

package springMaven.springMaven;/** * Spring bean *  */public class HelloWorld {private String name;private String passwd;public HelloWorld(String name, String passwd) {this.name = name;this.passwd = passwd;}public void setPasswd(String passwd) {this.passwd = passwd;}public void setName(String name) {this.name = name;}public void printHello() {System.out.println("Hello ! " + name + ";" + passwd);}}

4、添加配置文件:spring-Module.xml,其中一个是属性注入,一个是构造函数注入:

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="helloBean" class="springMaven.springMaven.HelloWorld"><property name="name" value="busymonkey" /><property name="passwd" value="123456" /><constructor-arg type="java.lang.String" value="busymonkey1" /><constructor-arg type="java.lang.String" value="654321" /></bean></beans>

5、文件目录如下:



6、App类:

package springMaven.springMaven;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * Hello world! * */public class App {    public static void main( String[] args )    {        System.out.println( "Hello World!" );        ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");HelloWorld obj = (HelloWorld) context.getBean("helloBean");obj.printHello();    }}


注:属性注入的优先级大于构造函数的优先级,配置文件中的参数,跟bean类中的方法(set方法和构造函数方法)都是对应的,缺一不可。

0 0
原创粉丝点击