2.通过调用构造方法创建POJO
今天周六,来记一下昨天的学习笔记。
通过调用构造放在IoC容器中创建POJO实例或bean也是常见的一种方式,相当于在Java中使用new运算符创建对象;具体步骤如下:
step1:创建一个Java类;
step2:创建一个配置类,调用构造方法创建POJO实例;
step3:在测试类中,实例化IoC容器并扫描带有注解的Java类,POJO实例或bean实例会变成可访问的,并成为应用的一部分;
接下来,通过代码来理解一下;
step1:假设需要开发一个商城来在线销售产品,首先需要创建一个产品类(Product),有产品名和价格两个属性,由于商城中的产品种类很多,可以把产品类设置为抽象类,具体的产品类和继承该抽象类,抽象类Product的定义如下,
1 package com.apress.springrecipes.shop; 2 3 public abstract class Product { 4 private String name; 5 private double price; 6 7 public Product(){ 8 } 9 10 public Product(String name,double price){ 11 this.name = name; 12 this.price = price; 13 } 14 15 public void setName(String name) { 16 this.name = name; 17 } 18 19 public void setPrice(double price) { 20 this.price = price; 21 } 22 23 public String getName() { 24 return name; 25 } 26 27 public double getPrice() { 28 return price; 29 } 30 }
再创建两个子类Battery和Disc,继承抽象类Product,定义代码如下,
1 package com.apress.springrecipes.shop; 2 3 public class Battery extends Product{ 4 private boolean rechargeable; 5 6 public Battery(){ 7 super(); 8 } 9 10 public Battery(String name,double price){ 11 super(name,price); 12 } 13 14 public boolean isRechargeable() { 15 return rechargeable; 16 } 17 18 public void setRechargeable(boolean rechargeable) { 19 this.rechargeable = rechargeable; 20 } 21 }
1 package com.apress.springrecipes.shop; 2 3 public class Disc extends Product{ 4 private int capacity; 5 6 public Disc(){ 7 super(); 8 } 9 10 public Disc(String name,double price){ 11 super(name,price); 12 } 13 14 public int getCapacity() { 15 return capacity; 16 } 17 18 public void setCapacity(int capacity) { 19 this.capacity = capacity; 20 } 21 }
step2:创建配置类,注意写上@Configuration和@Bean,如下所示,
1 package com.apress.springrecipes.shop; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 6 @Configuration 7 public class ShopConfiguration { 8 @Bean 9 public Product aaa(){ 10 Battery p1 = new Battery("AAA",2.5); 11 p1.setRechargeable(true); 12 return p1; 13 } 14 15 @Bean 16 public Product cdrw(){ 17 Disc p2 = new Disc("CD-RW",1.5); 18 p2.setCapacity(700); 19 return p2; 20 } 21 }
step3:接下来,编写如下的Main类,通过从Spring IoC容器中获取产品来进行测试,
1 package com.apress.springrecipes.shop; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.annotation.AnnotationConfigApplicationContext; 5 6 public class Main { 7 public static void main(String[] args) throws Exception{ 8 ApplicationContext context = 9 new AnnotationConfigApplicationContext(ShopConfiguration.class); 10 Product aaa = context.getBean("aaa",Product.class); 11 Product cdrw = context.getBean("cdrw",Product.class); 12 System.out.println(aaa); 13 System.out.println(cdrw); 14 } 15 }
运行结果如下所示,

从结果可说明,直接打印类的输出为:包路径@地址
今天的博客写完了,看着窗外阳光明媚,一会把床垫搬楼顶上晒一晒,下午去鼓浪屿放松一下心情,网友们明天见!

浙公网安备 33010602011771号