[Spring of JAVAEE Series] 2003 Create and Use Bean

Bean s are often used to configure relevant information or to rely on injection to prevent hard coding and better unit testing.

Bean management is done by Spring. When a Bean object is needed, Spring intercepts your request and returns the existing Bean object to you instead of creating a new object, which controls the life cycle of the Bean object.

 

[Create Beans with @Bean]

Let's try to create a configuration class that returns the database connection source DataSource we want:

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

    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/db1");
    dataSource.setUsername("root");
    dataSource.setPassword("123");
    return dataSource;
}

 

First, a dataSource is created, and then the connection string, className, username password and other information are configured.

By default, the name of the Bean is the same as the method name, which can be modified by the name parameter:

@Bean(name="theSource")
public DataSource dataSource() {
...

Lifecycle can also be set:

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public DataSource dataSource() {
...

 

[Create Bean s with @Component]

@ Bean s are often used to configure classes, and @Component has a broader scope.

We create a Bean under the com.springapp.services package:

@Component
public class UserService {
    public int findNumberOfUsers() {
        return 10;
    }
}

This Bean is a basic method, returning the number of users, we do not involve the database, to rely on injection as a priority.

How can spring know that we have this Bean?

Add package scan:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.springcookbook.controller", "com.springcookbook.service"})
public class AppConfig {

}

Similarly, we can name it:

@Component('anAmazingUserService')
public class UserService {

}

 

@ Controller is often used for controller classes

@ Service is used for service classes, business logic classes

@ Repository for persistent classes

 

[Use Bean]

1. Inject Bean with AutoWired:

@Autowired
UserService userService;

2. Using Bean Objects

@Controller
public class HelloController {

  @Autowired
  UserService userService;

  @RequestMapping("/hello")
  @ResponseBody
  public String hi() {
    return "Hello from Maven project!" + "There are " + userService.getUserNums() +"users.";
  }
}

 

3. Effect

[Manual Bean Injection]

 

1. Introducing Application Context

@Autowired
private ApplicationContext applicationContext;

 

2. Use ApplicationContext to get objects by name

UserService userService = (UserService)applicationContext.getBean("userService");

 

[Dismantling allocation files]

1. Create configuration file classes

@Configuration
public class DatabaseConfig {
...

 

2. Register the configuration class to ServletInitializer

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[]{AppConfig.class, DatabaseConfig.class};
}

 

Tags: Spring Database MySQL JDBC

Posted on Fri, 09 Aug 2019 02:20:56 -0700 by vietnamese