Java 创建对象方法的演变
1、普通 Java 代码
public class Rectangle {private int width;private int length;public Rectangle() {System.out.println("Hello World!");}public void setWidth(int widTth) {this.width = widTth;}public void setLength(int length) {this.length = length;}@Overridepublic String toString() {return "Rectangle{" +"width=" + width +", length=" + length +'}';}public static void main(String[] args) {Rectangle rectangle = new Rectangle();rectangle.setLength(3);rectangle.setWidth(2);}
}
2、Spring
-
编写配置文件:
第一段是命名空间
第二段是我们自己的 bean,需要给 bean 指定 id(对象的唯一标识,不可重复),class(实现的类的全限定名),属性赋值(set 后面的属性)。 -
通过 ClassPathXmlApplicationContext 调用 Bean,可以通过三种方式调用:id(需要强转)/ class(需要 bean 是单例的)/ id + class 。
public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("service.xml");// 通过 idRectangle rectangle1 = (Rectangle) context.getBean("rectangle");// 通过 classRectangle rectangle2 = context.getBean(Rectangle.class);// 通过 id + classRectangle rectangle3 = context.getBean("rectangle",Rectangle.class);System.out.println(rectangle1);}
3、Spring Boot
- 定义一个类
- 定义Config 配置类,并通过注解将其注册为 Bean,如@Component,@Bean,@Service等。
- 之后就能在其他类中通过 @Autowired 或 @Resource 注入使用
@Data
@AllArgsConstructor
public class Rectangle {private int width;private int length;public Rectangle() {System.out.println("Hello World!");}@Overridepublic String toString() {return "Rectangle{" +"width=" + width +", length=" + length +'}';}
}public class RectangleConfig {@Beanpublic Rectangle rectangle(){return new Rectangle(3,4);}
}@RestController
public class MyController {@Autowiredpublic Rectangle rectangle;@GetMapping("/bean")public String getBeanDetails() {return rectangle.toString();//Rectangle{width=3, length=4}}
}