1. Annotation
(1) Traditional annotation
Annotation | Description |
---|---|
@Component | Used on classes to instantiate Beans |
@Controller | Used on web layer classes to instantiate Beans |
@Service | Used on the service layer class to instantiate Bean |
@Repository | Used on dao layer classes to instantiate beans |
@Autowired | Used on fields for type dependency injection |
@Qualifer | Used in conjunction with @Autowired, fields are used for dependency injection based on name |
@Resource | Equivalent to @Autowired + @Qualifer, inject according to name |
@Value | Inject ordinary attributes |
@Scope | Mark the scope of the Bean |
@PostConstruct | Use to mark the scope of the Bean The method is the initialization method of the Bean |
@PreDestroy | Use the method to mark the method as the destruction method of the Bean |
(2) New annotation
The above annotations cannot completely replace the xml configuration file. The configurations that need to be replaced by annotations are as follows:
-
Non-custom Bean configuration:
-
Load the configuration of the properties file:
-
Configuration of component scan:
-
Introduce other configuration files:
Annotation | Description |
---|---|
@Configuration | Used to specify that the current class is a Spring configuration class, and annotations will be loaded from this class when the container is created |
@ComponentScan | Used to specify Spring Packages to scan when initializing the container. The function is the same as |
@Bean | Used on a method, the annotation stores the return value of the method in the Spring container |
@PropertySource | is used to load the .properties file Configuration |
@Import | is used to import other configuration classes |
2. Establish a database connection
(1). Create the database gcxy_teach, and create the table according to the following sql
SET FOREIGN_KEY_CHECKS=0; ---------------------------- -- Table structure for `phone` ---------------------------- DROP TABLE IF EXISTS `phone`; CREATE TABLE `phone` ( `phone_id` bigint NOT NULL AUTO_INCREMENT COMMENT 'Mobile phone number', `brand_id` bigint NOT NULL COMMENT 'Brand number', `model_number` varchar(50) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'model', `capacity` int NOT NULL COMMENT 'Storage capacity', PRIMARY KEY (`phone_id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; ---------------------------- -- Records of phone ---------------------------- INSERT INTO `phone` VALUES ('1', '1', 'mate60', '256'); INSERT INTO `phone` VALUES ('2', '1', 'p60', '128'); INSERT INTO `phone` VALUES ('3', '2', 'x50', '128');
(2).Import the coordinates required for the project
<dependencies> <!-- spring related coordinates --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.8</version> </dependency> <!-- mysql driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> <!-- spring integrates jdbc related coordinates --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.8</version> </dependency> <!-- spring integrates junit related coordinates --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.8</version> </dependency> <!-- druid connection pool--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.4</version> </dependency> <!-- junit test--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>2.5.1</version> </dependency> </dependencies> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties>
(3) Create the file jdbc.properties in the resources folder
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql:///gcxy_teach?serverTimezone=Asia/Shanghai &characterEncoding=utf-8 jdbc.username=root jdbc.password=123456
(4) Create a Spring configuration class and use the @PropertySource annotation to load the properties file
@Configuration @PropertySource("classpath:jdbc.properties") public class SpringConfiguration { }
(5) Use @Bean annotation to configure the data source (connection pool)
@Configuration @PropertySource("classpath:jdbc.properties") public class SpringConfiguration { @Value("${jdbc.url}") private String jdbcUrl; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Value("${jdbc.driver}") private String driverClassName; @Bean public DataSource dataSource() { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(jdbcUrl); hikariConfig.setUsername(username); hikariConfig.setPassword(password); hikariConfig.setDriverClassName(driverClassName); return new HikariDataSource(hikariConfig); } }
(6) Write test classes and test methods for testing
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {SpringConfiguration.class}) public class DataSourceTest { @Autowired private DataSource dataSource; @Test public void testDataSource() throws SQLException { Connection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); } }
3. Configure the use of JdbcTemplate to query data from the database
(1) Create entity class under com.cqgcxy.entity package
public class Phone { // phone_id bigint private Long phoneId; // brand_id bigint private Long brandId; // model_number varchar private String modelNumber; // capacity int private Integer capacity; public Long getPhoneId() { return phoneId; } public void setPhoneId(Long phoneId) { this.phoneId = phoneId; } public Long getBrandId() { return brandId; } public void setBrandId(Long brandId) { this.brandId = brandId; } public String getModelNumber() { return modelNumber; } public void setModelNumber(String modelNumber) { this.modelNumber = modelNumber; } public Integer getCapacity() { return capacity; } public void setCapacity(Integer capacity) { this.capacity = capacity; } @Override public String toString() { return "Phone{" + "phoneId=" + phoneId + ", brandId=" + brandId + ", modelNumber='" + modelNumber + ''' + ", capacity=" + capacity + '}'; } }
(2) Use the @Bean tag to configure JdbcTemplate into the spring container
@Configuration @PropertySource("classpath:jdbc.properties") public class SpringConfiguration { @Value("${jdbc.url}") private String jdbcUrl; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Value("${jdbc.driver}") private String driverClassName; @Bean public DataSource dataSource() { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(jdbcUrl); hikariConfig.setUsername(username); hikariConfig.setPassword(password); hikariConfig.setDriverClassName(driverClassName); return new HikariDataSource(hikariConfig); } @Bean public JdbcTemplate getJdbcTemplate(DataSource dataSource){ JdbcTemplate jt = new JdbcTemplate(); jt.setDataSource(dataSource); return jt; } }
(3) Write the test method testJdbcTemplate in the DataSourceTest test class for testing
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {SpringConfiguration.class}) public class SpringConfigurationTest extends TestCase { @Autowired private JdbcTemplate jt; @Test public void testJdbcTemplate(){ List<Phone> phoneList = jt.query("select * from phone", new BeanPropertyRowMapper<Phone>(Phone.class)); phoneList.forEach(s-> System.out.println(s)); } }
4. Build a three-tier architecture:
(1) Create data access layer: dao interface and implementation class:
-
Create the PhoneDao interface under the com.cqgcxy.dao package
public interface PhoneDao { List<Phone> select(); }
-
Create the PhoneDaoImpl implementation class under the com.cqgcxy.dao.impl package.
@Repository public class PhoneDaoImpl implements PhoneDao { @Autowired private JdbcTemplate jdbcTemplate; public List<Phone> select() { return jdbcTemplate.query("select * from phone", new BeanPropertyRowMapper<Phone>(Phone.class)); } }
(2) Create the business logic layer: service interface and implementation class
-
Create the PhoneService interface under the com.cqgcxy.service package
public interface PhoneService { List<Phone> getPhones(); }
-
Create a PhoneServiceImpl implementation class under the com.cqgcxy.service.impl package.
@Service public class PhoneServiceImpl implements PhoneService { @Autowired private PhoneDao phoneDao; public List<Phone> getPhones() { return phoneDao.select(); } }
(3) Create the presentation layer: controller class under the com.cqgcxy.controller package
@Controller public class PhoneController { @Autowired private PhoneService phoneService; public List<Phone> getAll() { return phoneService.getPhones(); } }
(4) Configure annotation scanning on Spring’s configuration class.
@Configuration @PropertySource("classpath:jdbc.properties") @ComponentScan(basePackages = "com.cqgcxy") // Modify to your package path public class SpringConfiguration { @Value("${jdbc.url}") private String jdbcUrl; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Value("${jdbc.driver}") private String driverClassName; @Bean public DataSource dataSource() { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(jdbcUrl); hikariConfig.setUsername(username); hikariConfig.setPassword(password); hikariConfig.setDriverClassName(driverClassName); return new HikariDataSource(hikariConfig); } @Bean public JdbcTemplate getJdbcTemplate(DataSource dataSource){ JdbcTemplate jt = new JdbcTemplate(); jt.setDataSource(dataSource); return jt; } }
(5) Select the PhoneController class and press ctrl + shift + T to create the corresponding JUnit4 test class and test method for this class.
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {SpringConfiguration.class}) public class PhoneControllerTest { @Autowired private PhoneController phoneController; @Test public void getAll() { List<Phone> phoneList = phoneController.getAll(); phoneList.forEach(s-> System.out.println(s)); } }
The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java skill treeAnnotationsBasic grammar 139356 people are learning the system