简体   繁体   中英

Spring: how to inject field with annotations

I have class inherit JFrame.

public class MainFrame extends JFrame {
    public void init() {
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setSize(new Dimension(600, 400));

        setVisible(true);
        setState(Frame.NORMAL);
        show();
    }
}

Spring config for this bean

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" 
          "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="mainFrame" class="todo.ui.MainFrame" init-method="init">
  </bean>
</beans>

class JFrame have private field title. Title set from xml config

<bean id="mainFrame" class="todo.ui.MainFrame" init-method="init">
    <property name="title">
      <value>My To Do List</value>
    </property>
  </bean>

How to inject private field with annotation?

You have to use @Value annotation:

public class MainFrame extends JFrame {

  @Value("my title")
  private String title;

or if the value is some dynamic variable then you use:

@Value("#{beanA.title}")
  private String title;

Update

If you have to set to the parent then:

      @Value("my title")
      @Override
      public void setTitle(String title){
         super.setTitle(title);
      }

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