gpt4 book ai didi

java - 通过注解进行依赖注入(inject)

转载 作者:行者123 更新时间:2023-12-04 06:01:33 25 4
gpt4 key购买 nike

我是spring的新用户。我正在尝试通过注释来实现依赖注入(inject)。我的
beans.xml 是:-

<!-- Add your classes base package here -->          
<context:component-scan base-package="com.springaction.chapter01"/>

<bean id="greeting" class="com.springaction.chapter01.GreetingImpl">
<property name="greeting">
<value>Naveen Jakad</value>
</property>
</bean>

我要注入(inject)的bean是:-
package com.springaction.chapter01;

import org.springframework.stereotype.Service;

@Service
public class InjectBean {

private int id;
private String name;

public InjectBean() {
super();
}
//setter getter of above instance variables..
}

我想在上面注入(inject)的bean是:-
package com.springaction.chapter01;

import org.springframework.beans.factory.annotation.Autowired;

public class GreetingImpl implements Greeting {

private String greeting;

@Autowired
private InjectBean myBean;

public GreetingImpl() {
super();
}
public GreetingImpl(String greeting) {
super();
this.greeting = greeting;
}

public void setGreeting(String greeting) {
this.greeting = greeting;
}

@Override
public void sayGreeting() {
System.out.println(greeting + " " + myBean);
}
}

所以当我通过以下方式测试上面的代码时: -
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("config.xml"));
Greeting greeting = (Greeting)beanFactory.getBean("greeting");
greeting.sayGreeting();

我得到输出“Naveen Jakad null”,简而言之,我无法实现我的目标。所以请帮助我,让我知道我在哪里犯错

最佳答案

如果你想通过 @Autowired 注入(inject)你不需要在 xml 中配置它:)

你需要设置

<mvc:annotation-driven />
<context:component-scan base-package="com.your.base.package" />

这样 Spring 就会知道检查注释

关于java - 通过注解进行依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8860660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com