0
点赞
收藏
分享

微信扫一扫

Java Spring Tutorial -- autowire自动装配

金穗_ec4b 2023-05-09 阅读 33


文件结构:

Java Spring Tutorial -- autowire自动装配_xml


package com.zxl.aop;

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

import com.zxl.aop.service.ShapeService;

public class AppMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
		//ShapeService shapeService=(ShapeService)ctx.getBean("shapeService");
		ShapeService shapeService=ctx.getBean("shapeService",ShapeService.class);
		System.out.println(shapeService.getCircle().getName());
		
	}

}

package com.zxl.aop.model;

public class Circle {
	private String name;

	public String getName() {
		return name;
	}

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

package com.zxl.aop.model;

public class Triangle {
	private String name;

	public String getName() {
		return name;
	}

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

package com.zxl.aop.service;

import com.zxl.aop.model.Circle;
import com.zxl.aop.model.Triangle;

public class ShapeService {
	private Circle circle;
	private Triangle triangle;
	
	public Circle getCircle() {
		return circle;
	}
	public void setCircle(Circle circle) {
		this.circle = circle;
	}
	public Triangle getTriangle() {
		return triangle;
	}
	public void setTriangle(Triangle triangle) {
		this.triangle = triangle;
	}
}

<?xml version="1.0" encoding="GBK"?>

<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 name="triangle" class="com.zxl.aop.model.Triangle">
        <property name="name" value="triangle name"/>
    </bean>
    
    <bean name="circle" class="com.zxl.aop.model.Circle">
        <property name="name" value="Circle name"/>
    </bean>
    <!-- autowire自动装配 -->
    <bean name="shapeService" class="com.zxl.aop.service.ShapeService" autowire="byName" />
      
</beans>












举报

相关推荐

0 条评论