设计模式单例模式: 单例模式(singleton Pattern)是指确保一个类在任何情况下都绝对只有一个实例,并提供一个全局访问点。
从缓存中获取单例bean
从bean的实例中获取对象
Spring在启动的时候,会扫描所有需要Spring去管理的类,然后给他new一个对象,如果我需要用这个对象了,直接@Autowired。
//接口
public interface DemoService {public void show();
}
//实现类,这里需要加注解Service
@Service
public class DemoImpl implements DemoService {@Overridepublic void show() {System.out.println("123");}
}
//controlelr层,这里需要加controlelr(返回的是页面)或者RestController(返回的是数据)注解
@RestController
public class HelloController {@AutowiredDemoService demoService;@RequestMapping("hello")public String hello(){demoService.show();return "hello";}
}
前提(如果说我要使用Spring给new出来的对象,那么我这对象也要交给Spring去管理)
这种情况是自己手动new对象,或者是出现Autowired拿不到的时候(这个对象不是Spring创造出来的,而是我们手动new出来的),我们就可以用SpringFactoryUtils。getBean(TestController.class),强制从Spring工厂(容器)里取出来,然后赋值。
先从实例对象里面把要new的对象给他构造全参方法
public class DemoImpl1 implements DemoService {public DemoImpl1(HelloController helloController) {this.helloController = helloController;}private HelloController helloController;@Overridepublic void show() {System.out.println("DemoImpl1");}
}
用SpringFactoryUtils。getBean(TestController.class),强制从Spring工厂(容器)里取出来,然后赋值。
@RestController
public class HelloController {@RequestMapping("hello")public String hello(){DemoImpl1 demoImpl1 = new Bean(HelloController.class));demoImpl1.show();return "hello";}
}
可以
如果说一个接口有多个实现类,那么我在在用的时候怎么用?
用list去接
@RestController
public class HelloController {@AutowiredList<DemoService> demoServices;@RequestMapping("hello")public String hello(){for (DemoService demoService : demoServices) {demoService.show();}return "hello";}
}
用具体的实现类去用。
@RestController
public class HelloController {@AutowiredDemoImpl1 demoService;@RequestMapping("hello")public String hello(){demoService.show();return "hello";}
}
@RestController
public class HelloController {private static int count =0;@RequestMapping("hello")public String hello(){count++;System.out.println(count);DemoImpl1 demoImpl1 = new Bean(HelloController.class));demoImpl1.show();return "hello";}
}
每刷新一次页面,count都会+1,不加static的时候哦,count也会加1,看似并没有什么区别,但是
没有static的时候,count是给对象调用的
@RestController
public class HelloController {private int count =0;@RequestMapping("hello")public String hello(){count++; //这个是类创建单例产生的count,会一直加 System.out.println(count);HelloController helloController = new HelloController();System.out.unt);//这里是对象.count,这里的count不会加return "hello";}
}
有static的情况,count是给类用的
@RestController
public class HelloController {private static int count =0;@RequestMapping("hello")public String hello(){count++;System.out.println(count);System.out.println( unt);//两个count输出一样return "hello";}
}
本文发布于:2024-01-29 12:34:25,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170650286715319.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |