Java Spring Boot VS .NetCore (三)Ioc容器处理

心不动则不痛 提交于 2020-07-26 23:31:16

Java中Spring Ioc 的处理还是通过配置文件的方式来实现,容器的初始需要说到上下文对象

ApplicationContext这个类,通过ClassPathXmlApplicationContext 加载 Ioc容器Xml配置并通过该实例对象的GetBean来获取对象实例

下面我就这一块对比 Java 与 .NetCore的使用方式

容器处理

Java:

首先需要建立Spring Ioc的xml配置文件,配置Bean, 也可以通过 @Component 注解的方式实现

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
       <bean id="testUserServices" class="com.example.demo.Services.interfaces.Impl.UserServices" >
       </bean>

</beans>
 

结合之前的helloword例子,我们修改下代码 getBean通过Id得到,略掉了类相关代码

@RequestMapping("/helloworld")
    public String Index()
    {

        ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-ioc.xml");
        IUserServices servers= (IUserServices) ctx.getBean("testUserServices");
        return  servers.SayHello("张三");
    }

.NetCore:

core中添加了services.AddScoped<IUserServices, UserServices>(); 添加了相关类的注册,而Java中则是通过XML配置

[Route("~/helloworld")]
        public IActionResult Index()
        {
            var servers=(IUserServices) HttpContext.RequestServices.GetService(typeof(IUserServices));
            var model=  servers.FindByName("admin").Result;
            return View();
        }

这里可以看到 .NetCore 中的 GetServices 与 Java中的 getBean 其实也就是那么一回事

注册的种类 

Java:Java可以通过构造函数、属性注入的方式来注册

.NetCore:同理使用Autofac 也可实现上述,但是.NetCore 中的 Dependence Injection (DI) 一般为构造函数注册 ,但是属性注入需要特殊处理

 

Java的xml配置 :

在Bean中添加

属性注入:

<property name="testUserServices"  value="com.example.demo.Services.interfaces.Impl.UserServices"></property>

构造函数注入:

<constructor-arg name="testUserServices" value="com.example.demo.Services.interfaces.Impl.UserServices"></constructor-arg>

.NetCore中对注入这块个人觉得很方便的

属性注入

services.AddScoped<IDbProviderFactory>(p=> {
return new CreateDbProviderFactory() { Abc = new ABC(); } 
});

构造函数注入

在Startup中添加  services.AddScoped<IUserServices, UserServices>();

生命周期管理

Java 配置 Scope

scope="singleton"
scope="prototype"
scope="request"

singleton:单例模式,容器中只会存在一个实例

prototype:每次请求的每次访问生成一个实例

request:每一次请求生成一个实例

.NetCore中

services.AddSingleton
services.AddScoped
services.AddTransient

Singleton :单例模式

Scoped:每次请求的每次反问生成一个实例

 Transient:每次请求生成一个实例

 

先介绍到这里下面看下Java 这边的效果

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!