我不能在依赖注入中使用autowire byType进行注入?

我正在尝试使用自动连接byType进行注入,但是无法注入值。如果在汽车类Bean中也声明了引擎类Beans不能正常工作,但是如果我创建了不同的Beans文件,则它不起作用。

Car.java(pojo类)

package com.meet.Spring.AutoWiredDI;

public class Car {
    private String CarName;
    private Engine engine;


    public String getcarName() {
        return CarName;
    }
    public void setCarName(String carName) {
        CarName = carName;
    }
    public Engine getEngine() {
        return engine;
    }
    public void setEngine(Engine engine) {
        this.engine = engine;
    }
    @Override
    public String toString() {
        return "Car [CarName=" + CarName + ",engine=" + engine + "]";
    }
}

Engine.java(POJO类)

package com.meet.Spring.AutoWiredDI;

public class Engine {
    private String engineName;
    public Engine() {
        // TODO Auto-generated constructor stub
        System.out.println("Engine is Called");
    }

    public String getEngineName() {
        return engineName;
    }

    public void setEngineName(String engineName) {
        this.engineName = engineName;
    }

    @Override
    public String toString() {
        return "Engine [engineName=" + engineName + "]";
    }
}

CarEngineRun.java(主类)

package com.meet.Spring.AutoWiredDI;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClasspathXmlApplicationContext;

public class CarEngineRun {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext context=new ClasspathXmlApplicationContext("CarAutoWire.xml");
        Car c=(Car)context.getBean("c");
        System.out.println(c.toString());
    }
}

CarAutoWire.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
      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-3.0.xsd">
    <bean id="c" class="com.meet.Spring.AutoWiredDI.Car" autowire="byType">
        <property name="CarName" value="Audi"/>
    </bean>
</beans>

EnginAutoWired.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
      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-3.0.xsd">
      <bean id="Engine" class="com.meet.Spring.AutoWiredDI.Engine" autowire-candidate="true" >
        <property name="engineName" value="External Engine"></property>

    </bean>
</beans>

输出:-汽车[CarName = Audi,engine = null] 预期输出:-汽车[CarName = Audi,engine = External Engine]

mmtsky 回答:我不能在依赖注入中使用autowire byType进行注入?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3014070.html

大家都在问