Problems with @Autowired in Swing Annex



  • To write a small program, the instrument selected:

    1. swing for gui
    2. spring
    3. hibernate
    4. mysql

    And to make things more and less beautiful, and in case you had to change something, you tried to put it under a mvc hat. To keep up with the xml-confits, make most of the annotations.

    There's a simple swing form:

    public class MainFrame extends JFrame {
    

    public MainFrame() {}

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

    Container c = getContentPane();
    c.setLayout(null);
    c.setBounds(20,20,600,400);
    
    
    addComponents();
    
    setVisible(true);
    setState(Frame.NORMAL);
    

    }

    private void addComponents() {

    JPanel panel = new JPanel();
    panel.setBorder(new TitledBorder("Adding new hashtag"));
    panel.setBounds(20,20,340,50);
    panel.setLayout(new GridLayout(1, 3));
    
    
    JLabel label = new JLabel("Enter hashtag");
    panel.add(label);
    
    final JTextField textField = new JTextField();
    textField.setColumns(6);
    panel.add(textField);
    
    JButton button = new JButton("Click to add");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
    

    //Следующая строка скорее всего не самый лучший вариант. может кто-то подсажет как написать лучше
    (new HashtagController()).addNewHashTag(textField.getText());
    System.out.println("Added: " + textField.getText());
    }
    });
    panel.add(button);
    this.add(panel);

    }
    

    }

    Controller:

    @Component
    public class HashtagController {

    @Autowired
    private HashtagDAO hashtagDAO;
    
    public HashtagController() {
    }
    
    public Boolean addNewHashTag(String s){
        hashtagDAO.createNewHashtag(new Hashtag(s));
        return null;
    }
    

    }

    Class:

    @Repository
    public class HashtagDAOImpl implements HashtagDAO {

    private static final Logger logger = LoggerFactory.getLogger(HashtagDAOImpl.class);
    
    private SessionFactory sessionFactory;
    
    @Autowired
    public HashtagDAOImpl(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }
    
    @Override
    public void createNewHashtag(Hashtag hashtag) {
        Session session = this.sessionFactory.getCurrentSession();
        session.save(hashtag);
        logger.info("Hashtag added succcessfully. Hashtaname: " + hashtag.getTagname());
    }
    

    }

    spring-config:

    <?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.xsd">
    <!--<context:annotation-config />-->
    <context:component-scan base-package="ru.smirnov"/>

    &lt;bean id="mainFrame" class="ru.smirnov.gui.MainFrame" init-method="init" /&gt;
    
    &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
        &lt;property name="driverClassName" value="com.mysql.jdbc.Driver"/&gt;
        &lt;property name="url" value="jdbc:mysql://localhost:3306/keepinmind"/&gt;
        &lt;property name="username" value="root"/&gt;
        &lt;property name="password" value="root"/&gt;
    &lt;/bean&gt;
    
    &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;
          &lt;!-- class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" --&gt;
        &lt;property name="dataSource" ref="dataSource" /&gt;
        &lt;property name="packagesToScan" value="ru.smirnov.domain" /&gt;
        &lt;property name="hibernateProperties"&gt;
            &lt;props&gt;
                &lt;prop key="dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt;
            &lt;/props&gt;
        &lt;/property&gt;
    &lt;/bean&gt;
    

    </beans>

    In the launch, there'll be a form with a field where you can write something off the keyboard, but when the button is pressed, it'll fly out.

    Exception in thread "AWT-EventQue-0" java.lang.NullPointerException
    at ru.smirnov.controller.HashtagController.addNewHashTag(HashtagController.java:25)`

    I mean, HashtagDAO's not coming up.

    How do I fix it? And I'll hear your comments, advice and stuff.



  • In your example, you don't use DI, you create a copy of the class manually.

    (new HashtagController()).addNewHashTag(textField.getText());
    

    Of course, there's nothing to work with this approach, because the DI container doesn't know anything about your class copy. In order to inject DAO, it is necessary to initiate the context of the Spring and ask the bin out of it:

    final ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
    final HashtagDAO dao = (HashtagDAO) context.getBean("myDaoName");
    

    And then you can hand this DAO to the cotroller through the grid. Or hand over the controller to DI.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2