首页 \ 问答 \ 没有XML的Spring Bean Annotation(Spring Bean Annotation with no XML)

没有XML的Spring Bean Annotation(Spring Bean Annotation with no XML)

我正在尽力在这里使用很少甚至没有XML。 我做了一个非常简单的程序,但它不起作用。 希望有人可以帮助我。

public class App {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext ctx = new    
AnnotationConfigApplicationContext(Logger.class);

        Logger logger = ctx.getBean(Logger.class);

        logger.writeConsole("Hello there");
        logger.writeFile("Hi again");

        ctx.close();
    }

}

接口

public interface LogWriter {
    public void write(String text);
}

的FileWriter

public class FileWriter implements LogWriter {

    public void write(String text) {

    System.out.println("FileWriter: " + text);

   }

}

ConsoleWriter

 public class ConsoleWriter implements LogWriter{

      public void write(String text) {
      System.out.println("Console Writer: "+text);

   }

}

记录仪

public class Logger {

@Autowired
private ConsoleWriter consoleWriter;
@Autowired
private FileWriter fileWriter;

public void setConsoleWriter(ConsoleWriter consoleWriter) {
    this.consoleWriter = consoleWriter;
}

public void setFileWriter(FileWriter fileWriter) {
    this.fileWriter = fileWriter;
}


public void writeFile(String text) {
    fileWriter.write(text);
}

public void writeConsole(String text) {
    consoleWriter.write(text);
}

@Bean
public Logger getLogger(){
    return new Logger();
    }

}

错误

Jul 02, 2015 2:52:49 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@246b179d: startup date [Thu Jul 02 14:52:49 CEST 2015]; root of context hierarchy
Exception in thread "main" java.lang.NoSuchMethodError: org.springframework.core.GenericTypeResolver.resolveReturnTypeForGenericMethod(Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Class;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:650)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:575)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1344)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:356)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:327)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:644)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:73)
    at com.main.application.App.main(App.java:10)

这是我的XML文件,但我试图摆脱使用XML和注释,所以我把这个简单的理解程序作为实践。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.2.xsd">


    <context:annotation-config></context:annotation-config>

</beans>

I am doing my best to use little to no XML here. I have made a very simple program but it is not working. Hoping someone could help me out.

public class App {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext ctx = new    
AnnotationConfigApplicationContext(Logger.class);

        Logger logger = ctx.getBean(Logger.class);

        logger.writeConsole("Hello there");
        logger.writeFile("Hi again");

        ctx.close();
    }

}

Interface

public interface LogWriter {
    public void write(String text);
}

FileWriter

public class FileWriter implements LogWriter {

    public void write(String text) {

    System.out.println("FileWriter: " + text);

   }

}

ConsoleWriter

 public class ConsoleWriter implements LogWriter{

      public void write(String text) {
      System.out.println("Console Writer: "+text);

   }

}

Logger

public class Logger {

@Autowired
private ConsoleWriter consoleWriter;
@Autowired
private FileWriter fileWriter;

public void setConsoleWriter(ConsoleWriter consoleWriter) {
    this.consoleWriter = consoleWriter;
}

public void setFileWriter(FileWriter fileWriter) {
    this.fileWriter = fileWriter;
}


public void writeFile(String text) {
    fileWriter.write(text);
}

public void writeConsole(String text) {
    consoleWriter.write(text);
}

@Bean
public Logger getLogger(){
    return new Logger();
    }

}

Error

Jul 02, 2015 2:52:49 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@246b179d: startup date [Thu Jul 02 14:52:49 CEST 2015]; root of context hierarchy
Exception in thread "main" java.lang.NoSuchMethodError: org.springframework.core.GenericTypeResolver.resolveReturnTypeForGenericMethod(Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Class;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:650)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:575)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1344)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:356)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:327)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:644)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:73)
    at com.main.application.App.main(App.java:10)

This is my XML file but I am trying to get away from using XML and just annotations so I made this simple to understand program as practice.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.2.xsd">


    <context:annotation-config></context:annotation-config>

</beans>

原文:https://stackoverflow.com/questions/31185487
更新时间:2022-06-12 22:06

最满意答案

Web Api依靠IHttpControllerSelector选择用于处理请求的api控制器,其中有一个依赖IAssembliesResolver用于解析程序集以搜索api控制器的默认实现。

在最小的改变中,你可以用一个定制的实现来替换这个程序集解析器,它将为你加载其他库。

一个非常天真的例子可能如下所示:

public class CustomAssemblyResolver : IAssembliesResolver
{
    public List<string> PluginNames { get; set; }

    public CustomAssemblyResolver()
    {
        PluginNames = new List<string>();

        //Add the custom libraries here
        PluginNames.Add("Your_Second_Library");
    }

    public ICollection<Assembly> GetAssemblies()
    {
        var asms = AppDomain.CurrentDomain.GetAssemblies().ToList();
        foreach (var name in PluginNames)
        {

            var asmPath = System.IO.Path.Combine(HostingEnvironment.MapPath("~/"), name + ".dll");
            try
            {
                var asm= System.Reflection.Assembly.LoadFrom(asmPath);
                if(!asms.Contains(asm))
                    asms.Add(asm);
            }
            catch (Exception)
            {

            }
        }
        return asms;
    }
}

然后您可以用此代码替换默认的解析器

config.Services.Replace(typeof(IAssembliesResolver), new CustomAssemblyResolver());

在您的WebApiConfig类的Register方法中。

然后,将所有带有控制器类的附加库复制到bin目录,然后完成。

如果您需要进一步定制控制器选择,您可以自定义实现IHttpControllerSelector并以类似的方式替换现有的实现。


Web Api relies on the IHttpControllerSelector for choosing the api controller for handling a request, of which has a default implementation which relies on IAssembliesResolver for resolving the assemblies to search for the api controllers.

In the least minimum change, you can replace this assembly resolver with a custom implementation which will load other libraries for you.

A very naive example might look like the following:

public class CustomAssemblyResolver : IAssembliesResolver
{
    public List<string> PluginNames { get; set; }

    public CustomAssemblyResolver()
    {
        PluginNames = new List<string>();

        //Add the custom libraries here
        PluginNames.Add("Your_Second_Library");
    }

    public ICollection<Assembly> GetAssemblies()
    {
        var asms = AppDomain.CurrentDomain.GetAssemblies().ToList();
        foreach (var name in PluginNames)
        {

            var asmPath = System.IO.Path.Combine(HostingEnvironment.MapPath("~/"), name + ".dll");
            try
            {
                var asm= System.Reflection.Assembly.LoadFrom(asmPath);
                if(!asms.Contains(asm))
                    asms.Add(asm);
            }
            catch (Exception)
            {

            }
        }
        return asms;
    }
}

You can then replace the default resolver with this code

config.Services.Replace(typeof(IAssembliesResolver), new CustomAssemblyResolver());

inside your Register method of WebApiConfig class.

Then, copy all your additional libraries with controller classes to the bin directory and you are done.

If you need even further customization for controller selection, you can go for custom implementation of IHttpControllerSelector and replace the existing implementation in a similar fashion.

相关问答

更多
  • 你需要在注册MVC的路由之前注册web api的路由,所以基本上你的App_Start()函数应该是这样的: protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register);//WEB API 1st FilterConfig.RegisterGlobalFilters(GlobalFilters ...
  • 不幸的是,WebAPI不支持“开箱即用”的领域,比如MVC。 您需要替换DefaultHttpControllerSelector 。 详细信息在链接中 。 此外,您可以尝试使用AttributeRouting.WebApi nuget包( http://attributerouting.net )。 此功能已包含在WebAPI路线图中。 Unfortunately, WebAPI does not support areas "out of the box", like MVC. You'll need ...
  • 问题是你使用UrlParameter.Optional (这是一个ASP.NET MVC特定类型)而不是RouteParameter.Optional 。 改变你的路线如下,然后它应该工作: GlobalConfiguration.Configuration.Routes.MapHttpRoute( "Api", "api/{controller}/{id}", new { id = RouteParameter.Optional } ); The problem is that ...
  • 创建控制器后,只能很好地分配用户。 ApiControllers上没有可以处理的事件。 最常见的方法是提取一个方法来检索额外信息并在每个操作中调用它 The User is only assigned well after the controller is created. There are no events on ApiControllers that you can handle to do that. The most common way to this is to extract a met ...
  • 在本教程之后,当创建一个显示产品列表的页面时,我需要创建两个控制器=>一个用于常规网站(来自“Controller”),另一个用于通过API提供来自“API”的API请求控制器“? 这似乎有很多冗余。 是的,你需要2个控制器。 这可能是多余的,但现在就是这样。 希望Microsoft将在未来的版本中合并这两种开发方法。 目前,您还可以从Web API控制器返回Razor视图,但通过API控制器执行所有操作可能会有点痛苦。 Following this tutorial, when creating a pa ...
  • 在我看来,如果你使用WebAPI,你的标准MVC控制器不应该用于CRUD。 你的API控制器应该处理CRUD操作,你的MVC控制器应该返回视图。 通过这条路线,它可以为您提供几种不同的选项,以便您在视图中显示数据: 传统 如果你想坚持更传统的路线,你可以从你的MVC控制器调用你的WebAPI控制器服务器端,为模型对象提供水分并返回一个强类型的视图。 您可以通过使用HttpClient类或WebClient类来进行API调用并反序列化响应。 单页 如果你想尝试更“现代”的路线,你可以尝试danludwig提出 ...
  • 真正的RESTful Web Api应该是无状态的,这意味着它不应该跟踪客户端发起的任何状态,例如会话。 您可以选择仍然将MVC与RESTful Web API一起使用,然后在API控制器和MVC控制器之间使用过期令牌。 此令牌需要在每次调用时传递回Web API,并用于验证当前会话的真实性。 True RESTful Web Api's should be stateless, meaning it should not keep track of any state initiated from the ...
  • Autofac提供了一个简单的机制来实现我的要求。 我已经通过使用AutoFac Assembly Scanning解决了这个问题。 1)创建一个类并使用Module类扩展并覆盖Load方法。 在重写方法中注册依赖关系。 public class AModule : Module { protected override void Load(ContainerBuilder builder) { builder.Register(c => new AComponent()).As
  • Web Api依靠IHttpControllerSelector选择用于处理请求的api控制器,其中有一个依赖IAssembliesResolver用于解析程序集以搜索api控制器的默认实现。 在最小的改变中,你可以用一个定制的实现来替换这个程序集解析器,它将为你加载其他库。 一个非常天真的例子可能如下所示: public class CustomAssemblyResolver : IAssembliesResolver { public List PluginNames { ge ...
  • 除非我遗漏了你的问题,否则我会将这段代码重构为一个存在于UI项目中的Util类。 然后你的MVC控制器和WebAPI控制器都可以调用它。 这种方法符合Composition over inheritance设计原则 。 Unless I am missing something from your question, I would refactor that piece of code into a Util class that lives in your UI project. Then both y ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)