加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 获取@Service注释类的bean?

发布时间:2020-12-15 04:09:07 所属栏目:Java 来源:网络整理
导读:在我的Web应用程序中,我没有使用applicationContext.xml.如何获取@Service注释类的bean? 如果我在我的Web应用程序中使用了applicationContext.xml,则每次都必须加载applicationContext.xml以获取@Service注释类的bean. 我用这种方式 WebApplicationContext
在我的Web应用程序中,我没有使用applicationContext.xml.如何获取@Service注释类的bean?

如果我在我的Web应用程序中使用了applicationContext.xml,则每次都必须加载applicationContext.xml以获取@Service注释类的bean.

我用这种方式

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext);
ServerConnection  con = (ServerConnection ) ctx.getBean("con");

我的服务类将是,

@Service  or @Service("con")
public class ServerConnection {

    private  TServerProtocol tServerProtocol;
    private  URI uri;

    public TServerProtocol getServerConnection(){

        System.out.println("host :"+host+"nport :"+port);

        try {
            uri = new URI("tcp://" + host + ":" + port);
        } catch (URISyntaxException e) {
            System.out.println("Exception in xreating URI Path");
        }

        tServerProtocol = new TServerProtocol(new Endpoint(uri));
        return tServerProtocol;
    }
}

有没有其他方法来获得这个类的bean?

要么

在Spring3.x中核心应用程序和Web应用程序的情况下,获取@Service注释类的bean的正确方法是什么?

解决方法

如果使用基于注释的配置,则使用@Autowired按类型获取bean,或使用@Resource以获取bean的名称.对于任何特定属性,只使用其中一个(以避免混淆).

@Autowired
private ServerConnection connection;
@Resource(name = "con")
private ServerConnection connection;

There’s also @Inject,但我不喜欢这样,因为随着豆子数量的增加它变得不那么好了.因人而异.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读