简体   繁体   中英

Converting code to Spring annotations

I am in the process of converting non-Spring code into Spring (v3.2) code. I have read through the Spring documentation but I am having trouble wrapping my head around the following situation shown below.

Classes Foo and Buz are managed by Spring and are singletons. Class Bar and MyHyperlinkListener need to be managed by Spring and should be prototype (though I'm not sure how to annotate these correctly).

  • The instance of Buz inside of Bar is currently null because Bar is not being managed by Spring. How would these classes be correctly annotated to allow this? Does a Factory class for Bar need to be created, and what would that look like?

  • The constructor for Bar is being passed a 'this'(aka JFrame) from inside the Foo class. I am not sure how to modify the code to handle a 'this' in Spring. I'm guessing this is another Factory that accepts a JFrame, but I'm not sure how to code that.


    @Named
    public class Foo extends JFrame{
        private Bar bar;

        private void doSomeWork(int x){
             bar = new Bar( new MyHyperlinkListener(this), x);
        }
    }

    public class Bar extends JPanel{
        @Inject
        private Buz buz;

        public Bar(MyHyperlinkListener mhl, int x){
        }
    }

    public class MyHyperlinkListener implements HyperlinkListener{
      private JFrame frame;
      public MyHyperlinkListener(JFrame frame){
        this.frame=frame;
      }
      //...code omitted
    }

    @Named
    public class Buz{
    }

    @Configuration
    public class MyConfiguration{

    }

    public class RunMe{
        public static void main(String[] args){
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
            context.scan("myPackage");
            context.refresh();
            context.registerShutdownHook();
            Foo foo = context.getBean(Foo.class);
            foo.setVisible(true);
        }
    }



You could make the Bar class @Configurable , which will allow it to be managed by Spring whenever an instance is created.

@Configurable
public class Bar extends JPanel{
    @Inject
    private Buz buz;

    public Bar(MyHyperlinkListener mhl, int x){
    }
}

Alternatively, you can use a bean factory to create your instances of Bar . This will have the same effect:

@Configuration
public class BarFactory
{
  @Bean
  public Bar createBar(MyHyperlinkListener mhl, int x) {
    return new Bar(mhl, x);
  }
}

Both methods are valid, and mainly differ in how they expose the management. They will also allow the constructor you wish to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM