本文共 2637 字,大约阅读时间需要 8 分钟。
事实上,Spring 还支持自动依赖注入。
package shangbo.spring.example31;public interface MessageService { String getMessage();}
package shangbo.spring.example31;public class MessageServiceImpl implements MessageService { public String getMessage() { return "Hello World"; }}
package shangbo.spring.example31;public class MessagePrinter { private MessageService service; public void setService(MessageService service) { this.service = service; } public void printMessage() { System.out.println(service.getMessage()); }}
package shangbo.spring.example31;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App { public static void main(String[] args) { // 实例化 Spring IoC 容器 ApplicationContext context = new ClassPathXmlApplicationContext("example.xml", MessagePrinter.class); // 从容器中获得 MessagePrinter 的实例 MessagePrinter printer = context.getBean(MessagePrinter.class); // 使用对象 printer.printMessage(); }}
除此之外,我们还可以全局设定自动注入方式。
package shangbo.spring.example33;public interface MessageService { String getMessage();}
package shangbo.spring.example33;public class MessageServiceImpl implements MessageService { public String getMessage() { return "Hello World"; }}
package shangbo.spring.example33;import org.springframework.beans.factory.annotation.Autowired;public class MessagePrinter { private MessageService service; // 自动注入 @Autowired public void setService(MessageService service) { this.service = service; } public void printMessage() { System.out.println(service.getMessage()); }}
package shangbo.spring.example33;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class AppConfig { @Bean public MessageService messageService() { return new MessageServiceImpl(); } @Bean public MessagePrinter messagePrinter() { return new MessagePrinter(); }}
package shangbo.spring.example33;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App { public static void main( String[] args ) { // 实例化 Spring IoC 容器,也可以一次读取多个Java配置文件 ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); // 从容器中获得 MessagePrinter 的实例 MessagePrinter printer = context.getBean(MessagePrinter.class); // 使用对象 printer.printMessage(); }}
–
– 声 明:转载请注明出处 – Last Updated on 2017-05-23 – Written by ShangBo on 2017-05-23 – End