使用静态工厂创建bean演示:
再创建一个静态工厂类
package com.wjw.entity.factory;
import com.wjw.entity.User;
public class StaticFactory {
public static User getUser(){
return new User();
}
}
此时在xml中定义相应的bean可以使用静态工厂方法来实现
使用实例工厂创建bean示例:
package com.wjw.entity.factory;
import com.wjw.entity.User;
public class UserFactory {
public User getUser(){
return new User();
}
}
由于方法不是静态的,所以不能直接调用,只能先创建一个工厂的对象,然后通过对象再进行调用
测试:
package com.wjw;
import com.wjw.controller.WelcomeController;
import com.wjw.entity.User;
import com.wjw.service.WelcomeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.FileSystemXmlApplicationContext;
@Configuration
@ComponentScan(“com.wjw”)
public class Entrance {
public static void main(String[] args) {
System.out.println(“Hello World!”);
String xmlPath = “F:\Java\spring-framework-5.2.0.RELEASE\springdemo\src\main\resources\spring\spring-config.xml”;
ApplicationContext applicationContext = new FileSystemXmlApplicationContext(xmlPath);
WelcomeService welcomeService = (WelcomeService) applicationContext.getBean(“welcomeService”);
welcomeService.sayHello(“强大的spring框架”);
//得到无参构造函数创建的对象:
User user1a = (User) applicationContext.getBean(“user1”);
User user1b = (User) applicationContext.getBean(“user1”);
//得到静态工厂创建的对象:
User user2a = (User) applicationContext.getBean(“user2”);
User user2c = (User) applicationContext.getBean(“user2”);
//得到实例工厂创建的对象:
User user3a = (User) applicationContext.getBean(“user3”);
User user3b = (User) applicationContext.getBean(“user3”);
System.out.println(“无参构造函数创建的对象:” + user1a);
System.out.println(“无参构造函数创建的对象:” + user1b);
System.out.println(“静态工厂创建的对象:” + user2a);
System.out.println(“静态工厂创建的对象:” + user2c);
System.out.println(“实例工厂创建的对象:” + user3a);
System.out.println(“实例工厂创建的对象:” + user3b);
}
}
独家面经总结,超级精彩
本人面试腾讯,阿里,百度等企业总结下来的面试经历,都是真实的,分享给大家!
Java面试准备
准确的说这里又分为两部分:
- Java刷题
- 算法刷题
Java刷题:此份文档详细记录了千道面试题与详解;
.(img-qdUWhQaS-1720084357429)]
[外链图片转存中…(img-arvsToDD-1720084357430)]
Java面试准备
准确的说这里又分为两部分:
- Java刷题
- 算法刷题
Java刷题:此份文档详细记录了千道面试题与详解;
[外链图片转存中…(img-NPcrN3hp-1720084357430)]
[外链图片转存中…(img-xEgmJYWu-1720084357431)]