Swing 应用程序中的 Hibernate 和 Spring

发布于 2024-11-08 13:45:09 字数 3876 浏览 0 评论 0原文

我是编程新手。我的 Swing 应用程序有问题。我想会话出了问题。我使用 Hibernate 并通过 Spring 配置它。当我按下按钮时,我想向数据库添加信息,但我得到 NullPoinerException。也许我必须以另一种方式编写用户界面? 需要你的帮助!谢谢。

这是我的代码:

MainFrame.java

public class MainFrame extends JFrame {

    public MainFrame(){
        setTitle("Title");
        setSize(300,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        makeButtons();
        setVisible(true);
    }
    public void makeButtons(){
        JPanel panel=new JPanel();
        panel.add(makeLoginField());
        panel.add(makeLoginButton());
        panel.add(makePassField());
        panel.setVisible(true);
        this.add(panel);
    }
    public JButton makeLoginButton(){
        JButton loginButton=new JButton("Login");
        loginButton.addActionListener(new Action());
        return loginButton;
    }
    public JTextField makeLoginField(){
        JTextField loginField=new JTextField();
        loginField.setSize(new Dimension(134, 20));
        return loginField;
    }
    public JPasswordField makePassField(){
        JPasswordField passField=new JPasswordField();
        passField.setSize(new Dimension(134, 20));
        return passField;
    }
    public static void main(String[] args) {
         JFrame m=new MainFrame();   
    }   
}

Action.java

class Action implements ActionListener{
    @Autowired
    private UserServiceInterface userService;

    public void setuserService(UserServiceInterface userService) {
        this.userService=userService;
    }
    public void actionPerformed (ActionEvent e){
        User u=new User();
        u.setName("HellofromGUI");      
        userService.addUser(u);
    }
}

UserService.java

@Transactional
public class UserService implements UserServiceInterface{
    @Autowired
    private UserDaoInterface dao;

    public void setDao(UserDaoInterface dao) {
        this.dao = dao;
    }
    public void addUser(User u){
    dao.insertRow(u);
    }
    public List getData(){
        return dao.getDBValues();
    }
}

UserDao.java

public class UserDao implements UserDaoInterface{
    @Autowired
    private SessionFactory sessionFactory;

    public void insertRow(User user) {
        Session session = null;
        session = sessionFactory.getCurrentSession();
        session.save(user);

    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
     public List getDBValues() {
            Session session = sessionFactory.getCurrentSession();
            List<User> users = session.createCriteria(User.class).list();
            return users;
    }
}

beans.xml

<beans>

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

    <bean id="userdao" class="dao.UserDao">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="userservice" class="service.UserService">
        <property name="dao">
            <ref bean="userdao" />
        </property>
    </bean>
    <bean id="paymentdao" class="dao.PaymentDao">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="paymentservice" class="service.PaymentService">
        <property name="dao">
            <ref bean="paymentdao" />
        </property> 
    </bean>
    <bean id="usergui" class="ui.Action">
        <property name="userService">
            <ref bean="userservice" />
        </property> 
    </bean>
</beans>

I'm a newbie in programming.I have problems in my Swing application.I suppose something wrong with session.I use Hibernate and configure it by means of Spring.When I press button I want to add info to database but I get NullPoinerException.Maybe I must code user interface another way?
Need your help!Thanks.

Here my code:

MainFrame.java

public class MainFrame extends JFrame {

    public MainFrame(){
        setTitle("Title");
        setSize(300,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        makeButtons();
        setVisible(true);
    }
    public void makeButtons(){
        JPanel panel=new JPanel();
        panel.add(makeLoginField());
        panel.add(makeLoginButton());
        panel.add(makePassField());
        panel.setVisible(true);
        this.add(panel);
    }
    public JButton makeLoginButton(){
        JButton loginButton=new JButton("Login");
        loginButton.addActionListener(new Action());
        return loginButton;
    }
    public JTextField makeLoginField(){
        JTextField loginField=new JTextField();
        loginField.setSize(new Dimension(134, 20));
        return loginField;
    }
    public JPasswordField makePassField(){
        JPasswordField passField=new JPasswordField();
        passField.setSize(new Dimension(134, 20));
        return passField;
    }
    public static void main(String[] args) {
         JFrame m=new MainFrame();   
    }   
}

Action.java

class Action implements ActionListener{
    @Autowired
    private UserServiceInterface userService;

    public void setuserService(UserServiceInterface userService) {
        this.userService=userService;
    }
    public void actionPerformed (ActionEvent e){
        User u=new User();
        u.setName("HellofromGUI");      
        userService.addUser(u);
    }
}

UserService.java

@Transactional
public class UserService implements UserServiceInterface{
    @Autowired
    private UserDaoInterface dao;

    public void setDao(UserDaoInterface dao) {
        this.dao = dao;
    }
    public void addUser(User u){
    dao.insertRow(u);
    }
    public List getData(){
        return dao.getDBValues();
    }
}

UserDao.java

public class UserDao implements UserDaoInterface{
    @Autowired
    private SessionFactory sessionFactory;

    public void insertRow(User user) {
        Session session = null;
        session = sessionFactory.getCurrentSession();
        session.save(user);

    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
     public List getDBValues() {
            Session session = sessionFactory.getCurrentSession();
            List<User> users = session.createCriteria(User.class).list();
            return users;
    }
}

beans.xml

<beans>

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

    <bean id="userdao" class="dao.UserDao">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="userservice" class="service.UserService">
        <property name="dao">
            <ref bean="userdao" />
        </property>
    </bean>
    <bean id="paymentdao" class="dao.PaymentDao">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="paymentservice" class="service.PaymentService">
        <property name="dao">
            <ref bean="paymentdao" />
        </property> 
    </bean>
    <bean id="usergui" class="ui.Action">
        <property name="userService">
            <ref bean="userservice" />
        </property> 
    </bean>
</beans>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

把梦留给海 2024-11-15 13:45:09

使用 Spring 需要记住的重要一点是它只能将引用注入到 Spring 托管 bean 中。在您的代码中,您期望 Spring 将 UserService 实例注入到您的 Action 类中。 以下代码创建您自己的 Action 类实例:

loginButton.addActionListener(new Action());

Spring 应该正确执行对名为 usergui 的 Spring bean 的注入,但是,在您的 UI 中,您将使用 自己创建一个对象的实例,它不会由 Spring 管理,并且需要像任何自管理对象一样对待,即手动设置所有必需的引用。

为了获得您期望的结果,您需要更改 UI 逻辑以引用您在配置文件中定义的 Spring usergui bean。为了获得这个实例,您首先需要检索 Spring 的 BeanFactory 的实例。以下是您的代码如何检索 usergui` 的正确实例的示例:

// using ClassPathResource, you can also use a FileResource or other method to load config
Resource  res = new ClassPathResource("/beans.xml");
// initialize bean factory
BeanFactory  factory = new XmlBeanFactory(res);        

// retrieve Spring managed Action class
ActionListener action = factory.getBean("usergui", ActionListener.class);

// configure login button
loginButton.addActionListener(action);

示例代码引用了 ActionListener 而不是直接引用 Action 类。通常,在使用 Spring 时,您希望与类实现的接口 (ActionListener) 交互,而不是与类本身 (Action) 交互。这样做允许您更改 bean usergui 引用的实现,例如 Action -> DifferentAction,无需您修改 UI 代码。

The important thing to remember with Spring is that it can only inject references into Spring managed beans. In your code, you are expecting that Spring will inject an instance of UserService into you Action class. Spring should be correctly performing this injection into the Spring bean named usergui, however, in you UI you are creating your own instance of the Action class with the following code:

loginButton.addActionListener(new Action());

Anytime you create an instance of an Object yourself, it will not be managed by Spring and needs to be treated as you would any self managed object, i.e., set all required references manually.

To get the result you are expecting, you need to changed your UI logic to reference the Spring usergui bean that you defined in your configuration file. In order to get this instance, you first need to retrieve an instance of Spring's BeanFactory'. Here is an example of how your code can look to retrieve the correct instance ofusergui`:

// using ClassPathResource, you can also use a FileResource or other method to load config
Resource  res = new ClassPathResource("/beans.xml");
// initialize bean factory
BeanFactory  factory = new XmlBeanFactory(res);        

// retrieve Spring managed Action class
ActionListener action = factory.getBean("usergui", ActionListener.class);

// configure login button
loginButton.addActionListener(action);

The sample code referenced ActionListener rather than the Action class directly. Typically when using Spring, you want to interact with the Interface (ActionListener) implemented by a Class rather than the Class itself (Action). Doing so allows for you to change the implementation being referenced for the bean usergui, e.g., Action -> DifferentAction, without requiring you to modify your UI code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文