//这是基于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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="bs" class="com.dz147.Validator.BookServiceImpl"/> <bean id="bs2" class="com.dz147.Validator.BookServiceImpl2"/> </beans>
package com.dz147.Validator; public interface BookService { public void getInfo(); } //实现 public class BookServiceImpl implements BookService { @Override public void getInfo() { System.out.println("这是第一个实现"); } }
使用
public class TestSpring { public static void main(String[] args) { ClassPathXmlApplicationContext cc = new ClassPathXmlApplicationContext("spring/testSpring.xml"); Object bs = cc.getBean("bs2"); ((BookService)bs).getInfo(); } }
以上是基于XML
使用java注解
//使用java注解把对象放入Ioc容器中
@Configuration public class BookServiceJavaStyle { @Bean public BookService xxx(){ return new BookServiceImpl2(); } }
public class BookServiceImpl2 implements BookService { @Override public void getInfo() { System.out.println("这是第二个实现"); } }
public class TestSpring { public static void main(String[] args) { /*ClassPathXmlApplicationContext cc = new ClassPathXmlApplicationContext("spring/testSpring.xml"); Object bs = cc.getBean("bs2"); ((BookService)bs).getInfo();*/ //java注解方式 newJavaStyle(); } public static void newJavaStyle() { AnnotationConfigApplicationContext acc = new AnnotationConfigApplicationContext(BookServiceJavaStyle.class); acc.getBean(BookService.class).getInfo(); } }