For writing a small program as a tool I chose:

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

And yet, so that everything was more or less beautiful, and in case it was necessary to change something, I tried to fit everything into an mvc-template. In order not to fool around with xml-configs, I did most of the annotations.

There is some simple swing shape:

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; } } 

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

When you start, a form with a field appears where you can type in something from the keyboard, but when you click the (Add) button, it crashes.

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

i.e., HashtagDAO is not picked up.

How to fix,? And in general I will listen to your comments, advice and the like.

  • Please adhere to the accepted practice regarding greetings . Yes, and the title would be good to give a more appropriate error. - aleksandr barakin
  • And why does the method returning Boolean return null ? There are suspicions that an exception is thrown due to the fact that you have not initialized hashtagDAO . - LEQADA
  • @LEQADA, while this does not play a special role, because the return value is nowhere used. - I. Smirnov
  • @LEQADA is understandable, which is uninitialized. The question is how to do it using spring features. The trick is that you can, of course, initialize through the constructor, but then, as for me, the problem will appear during the initialization of the HashtagController itself in gui. - I. Smirnov
  • If you do not need many copies of the HashtagController, then make the HashtagController hashtagController field in the MainFrame and pull up its @Autowired annotation. Then call not (new HashtagController ()), but hashtagController - Chubatiy

1 answer 1

In your example, you are not using DI, but create an instance of the class manually.

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

Naturally, with this approach, nothing will work, because the DI container knows nothing and cannot know about your instance of the class. To inject a DAO, you need to initialize the context of the spring and query the beans from it:

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

And then you can transfer this DAO to the controller through the setter. Or give the controller under the control of DI.