Kiedy należy tworzyć Beany?

0

Kiedy i jak należy tworzyć beany o co z nimi chodzi? Czy dla każdej klasy w której będę chciał skorzystać UserService muszę tworzyć beana i powtarzać ten kod:

		try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {

			ctx.scan(CONFIG_PACKAGE);
			ctx.refresh();

			UserService bean = ctx.getBean(UserService.class);
			UserController bean2 = ctx.getBean(UserController.class);
			bean2.btnSaveUser(new User("Jan", "Dwa", "5342"));
			// userController.btnSaveUser();
		}
package com.my.app;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.my.app.configuration.*;
import com.my.app.controller.UserController;
import com.my.app.model.User;
import com.my.app.service.UserService;

public class Main {

	private static final String CONFIG_PACKAGE = "com.my.app.configuration";

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {

			ctx.scan(CONFIG_PACKAGE);
			ctx.refresh();

			UserService bean = ctx.getBean(UserService.class);
			UserController bean2 = ctx.getBean(UserController.class);
			bean2.btnSaveUser(new User("Jan", "Dwa", "5342"));
			// userController.btnSaveUser();
		}
	}

} 
 
package com.my.app.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.jolbox.bonecp.BoneCPDataSource;
import com.my.app.controller.UserController;
import com.my.app.service.UserService;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.my.app.repository")
@PropertySource("classpath:application.properties")
public class DataJpaConfig {

	protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
	protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
	protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
	protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

	private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
	private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
	private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
	private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
	private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";

	private static final String PROPERTY_PACKAGES_TO_SCAN = "com.my.app.model";

	@Autowired
	private Environment environment;

	@Bean
	public DataSource dataSource() {
		BoneCPDataSource dataSource = new BoneCPDataSource();

		dataSource.setDriverClass(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
		dataSource.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
		dataSource.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
		dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

		return dataSource;
	}

	@Bean
	public JpaTransactionManager transactionManager() {
		JpaTransactionManager transactionManager = new JpaTransactionManager();

		transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

		return transactionManager;
	}

	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
		LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

		entityManagerFactoryBean.setDataSource(dataSource());
		entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
		entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);

		Properties jpaProperties = new Properties();
		jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT,
				environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
		jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL,
				environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
		jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO,
				environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
		jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY,
				environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
		jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL,
				environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

		entityManagerFactoryBean.setJpaProperties(jpaProperties);

		return entityManagerFactoryBean;
	}


	@Bean
	public UserService userServiceBean() {
		return new UserService();
	}
	
	@Bean
	public UserController uControllerBean(){
		return new UserController();
	}
}

 
package com.my.app.controller;

import org.springframework.beans.factory.annotation.Autowired;

import com.my.app.model.User;
import com.my.app.service.UserService;

public class UserController {
	
	@Autowired
	private UserService userService;
	
	public void btnSaveUser(User user){
		userService.saveUser(user);
	}
}

 
 
package com.my.app.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.my.app.model.User;

public interface UserRepository extends JpaRepository<User, Long>  {

}

 
package com.my.app.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.my.app.model.User;
import com.my.app.repository.UserRepository;

@Service
public class UserService {
	
	@Autowired
	private UserRepository userRepository;
	
	public User saveUser(User user){
		return userRepository.save(user);
	}

}
0

Nie. Inne klasy które są zarządzane przez kontener (np. inne serwisy) mają mieć @Autowire albo @Inject i tyle. A obiekty nie zarządzane, jeśli już muszą z tego serwisu korzystać, to muszą go dostać jako parametr.

0

Nie za bardzo umiem to zastosować w praktyce.

package com.my.app;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.my.app.controller.UserController;
import com.my.app.service.UserService;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

	private static final String CONFIG_PACKAGE = "com.my.app.configuration";

	@Override
	public void start(Stage stage) {

		final String nazwaprogramu = "RomaManager";
		try {
			Parent parent = FXMLLoader.load(getClass().getClassLoader().getResource("Test.fxml"));
			Scene scene = new Scene(parent);
			stage.setTitle(nazwaprogramu);
			stage.setScene(scene);
			stage.show();
			stage.setResizable(false);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {

			ctx.scan(CONFIG_PACKAGE);
			ctx.refresh();
			launch(args);
			UserService bean = ctx.getBean(UserService.class);

			UserController userController = new UserController(bean);
			// userController.setUserService(bean);

		} catch (Exception ex) {
			System.err.println(ex.getMessage());
		}
	}

}

 
package com.my.app.controller;

import java.net.URL;
import java.net.URL;
import java.net.URL;
import java.util.ResourceBundle;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.my.app.model.User;
import com.my.app.service.UserService;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;

public class UserController implements Initializable {

	private static final String CONFIG_PACKAGE = "com.my.app.configuration";
	
	@FXML
	private Button btnAddUser;

	@Autowired
	private UserService userService;
	
	//Domyślny konstruktor wymagany przez FX
	public UserController() {
		super();
	}
	
	

	public UserController(UserService userService) {
		super();
		this.userService = userService;
	}



	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void btnSaveUser(User user) {
		userService.saveUser(user);
	}

	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		// TODO Auto-generated method stub
		configureButtons();

	}

	private void configureButtons() {
		btnAddUser.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				// TODO Auto-generated method stub
				userService.saveUser(new User("Marcin", "Test", "500"));
				System.out.println("Test");

			}
		});
	}
}
 
 
	@Bean
	public UserService userServiceBean() {
		return new UserService();
	}

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at com.my.app.controller.UserController$1.handle(UserController.java:70)
at com.my.app.controller.UserController$1.handle(UserController.java:1)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$113/24313398.get(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(Unknown Source)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/2117255219.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

2

Nie znam sie na JavieFX ale powtórzę jeszcze raz: wstrzykiwanie jest dla obiektów ZARZĄDZANYCH przez kontener. Jak tworzysz obiekt przez new to nie możesz mieć w nim @Autowire bo NIE ZADZIAŁA. Twój kontroler też powinien być @Service tworzony przez Springa bo inaczej ten cały kod to jakiś WTF.

Zacznij może trochę od poczytania co to jest MVC bo jak widzę button w kontrolerze to aż mi smutno.

edit: zacznij może od jakiegoś exampla z internetów np. https://github.com/mehmetsunkur/SpringJavaFXController

Bo teraz to mi sie wydaje że ty chcesz obiekt tej samej klasy stworzyć X razy, raz przez JavaFX, raz przez Springa i raz ręcznie ;]

1 użytkowników online, w tym zalogowanych: 0, gości: 1