data source
Considering the mobike and ofo in the real world, they can be vividly compared to two different "bicycle sources", and the basic idea of data source realization is the same as before, such as c3p0, druid is the most popular data source.
spring and data source
When using a data source in a project, you need to hand over the authority to control the data source to spring, and spring can fully manage the data source.
Under the guidance of decoupling design ideas , we distinguish between the configuration files of Spring and the data source and the configuration files of the data source itself. A small case is shown below.
Data source configuration file:
c3p0.driverDriver=com.mysql.jdbc.Driver
c3p0.url=jdbc:mysql://192.168.168.128:7006/travel
c3p0.user=root
c3p0.password=root
c3p0.initialSize=5
c3p0.maxActive=10
c3p0.maxWait=3000
Spring configuration file
In order to import external configuration files , you need to introduce the context namespace in the spring configuration file:
modify the spring configuration file options
<bean id="dataSourceC3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${c3p0.driverDriver}"></property>
<property name="jdbcUrl" value="${c3p0.url}"></property>
<property name="user" value="${c3p0.user}"></property>
<property name="password" value="${c3p0.password}"></property>
</bean>
According to the modular design idea , the data source configuration file is introduced into the overall configuration file
<import resource="classpath:applicationContext_dataSource.xml"></import>
The test example is as follows:
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
ComboPooledDataSource dataSourceC3p0=(ComboPooledDataSource) appContext.getBean("dataSourceC3p0");
System.out.println("XXXXXXXXX"+dataSourceC3p0);
dataSourceC3p0.close();
Data source successfully obtained
annotation
However, in many cases, these configuration files alone increase the development complexity of the entire project. In this case, how to simplify development has become an urgent problem that you all want to solve . The comment is that great apes must be in rapid development projects. An indispensable artifact, the emergence of annotations makes our development no longer have to face repeated spring configuration files, which will bring good news to everyone. Let's review the spring annotation development.
Spring annotations are divided into original annotations and new annotations.
Original comment
annotation | Description |
---|---|
@Component | Used on the class to instantiate Bean |
@Controller | Used on the web layer class to instantiate Bean |
@Service | Used on the service layer class to instantiate Bean |
@Repository | Used on the dao layer class to instantiate Bean |
@Autowired | Used on fields for dependency injection based on type |
@Qualifier | Used in conjunction with @Autowired for dependency injection based on name |
@Resource | Equivalent to @Autowired+@Qualifier, inject according to the name |
@Value | Inject common attributes |
@Scope | Mark the scope of Bean |
@PostConstruct | Use to mark the method as the initialization method of Bean |
@PreDestroy | Use to mark the method as the destruction method of Bean |
Notes: When using annotations for development, you need to configure component scanning in applicationContext.xml. The function is to specify which package and its subpackages Beans need to be scanned in order to identify the classes, fields, and methods configured with annotations.
<!--注解的组件扫描-->
<context:component-scan base-package="com.itheima"></context:component-scan>
The difference between @Component, @Repository, @Service, @Controller
**@Component is a general annotation, the other three annotations are extensions of this annotation, ** and have specific functions
- @Repository annotation in the persistence layer has the function of translating native exceptions thrown by database operations into spring persistence layer exceptions.
- The @Controller layer is an annotation of spring-mvc, which has the function of forwarding and redirecting requests.
- The @Service layer is an annotation of the business logic layer. This annotation just marks that the class is in the business logic layer.
The difference between @Autowired and @Resource
- Both @Autowired and @Resource can be used to assemble beans. Both can be written on the field or on the setter method.
- @Autowired is assembled by type by default (this annotation belongs to spring). By default, the dependent object must exist. If you want to allow null values, you can set its required attribute to false, such as: @Autowired(required=false), If we want to use name assembly, we can use it in combination with the @Qualifier annotation, as follows:
@Autowired
@Qualifier("userDao")
//@Resource(name="userDao")
private UserDao userDao;
In this case, we can understand it as @Autowired+@Qualifier=@Resource.
- @Resource (this annotation belongs to J2EE), the default is to assemble according to the name, the name can be specified by the name attribute, if the name attribute is not specified, when the annotation is written on the field, the field name is used by default for installation name search, if the annotation is written The attribute name is used by default on the setter method for assembly. When no bean matching the name is found, the assembly is performed according to the type. But it should be noted that once the name attribute is specified, it will only be assembled according to the name. E.g:
@Resource(name="userDao")
private UserDao userDao;
@value
@Value("#{}") indicates that SpEl expressions are usually used to obtain bean properties or call a method of bean. Of course, there are also
usage notes that can express the constant @Value("${xxxx}") annotation to read the value from the configuration file.
Notes: If the annotation method is used, the setter and getter methods can be omitted. If the xml configuration method is used, then Need to write Setter and Getter methods.
New annotation
Using the above annotations can not completely replace the xml configuration file, and the configuration that needs to be replaced by annotations is as follows:
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 the packages that Spring will scan when initializing the container. The effect is the same as <context:component-scan base-package="com.itheima"/> in Spring's xml configuration file |
@Bean | Used on the method, annotate the return value of the method to be stored in the Spring container |
@PropertySource | Used to load the configuration in the .properties file |
@Import | Used to import other configuration classes |
Annotation configuration small case
Use annotations instead of
pom dependent coordinates for all the xml configuration of the data source
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!--<scope>compile</scope>-->
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
<scope>compile</scope>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
</dependencies>
service layer
public interface UserService {
public void save();
}
@Service("userService")
public class UserServiceImpl implements UserService {
private String username;
private int age;
private List<String> course;
private Map<String, User> userMap;
@Resource(name = "userDao")
private UserDao userDao;
private Properties properties;
...
public void save() {
System.out.println("my name is:"+username);
System.out.println("my age is"+age);
System.out.println("my course lists is :"+course);
System.out.println("my favourite teachers is :"+userMap);
System.out.println("my hobby is "+properties);
userDao.save();
}
}
dao layers
public interface UserDao {
public boolean save();
}
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@PostConstruct
public void initMethod(){
System.out.println("初始化方法执行了......");
}
@PreDestroy
public void destroyMethod(){
System.out.println("销毁方法执行了.......");
}
public boolean save() {
System.out.println("调用了save方法。。。。。");
return false;
}
}
Data source configuration
//<context:property-placeholder location="classpath:c3p0.properties"/>
@PropertySource("classpath:c3p0.properties")
public class DataSourceConfiguration {
@Value("${c3p0.driverDriver}")
private String driver;
@Value("${c3p0.url}")
private String url;
@Value("${c3p0.user}")
private String user;
@Value("${c3p0.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(user);
dataSource.setPassword(password);
return dataSource;
}
}
Spring annotation file configuration
@Configuration
//<context:component-scan base-package="com.feitian"/>
@ComponentScan("com.feitian")
//<import resource="applicationContext_*.xml"/>在中括号中可以加入多个class
@Import({
DataSourceConfiguration.class})
public class SpringConfiguration {
}
Annotation test
public class Anno {
@Test
public void test01(){
ApplicationContext applicationContext= new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = (UserService) applicationContext.getBean("userService");
userService.save();
}
}
spring integrated junit
Spring integration annotation configuration file
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {
SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Test
public void test01(){
userService.save();
}
}
When spring needs to integrate xml configuration files, just replace ContextConfiguration
@ContextConfiguration("classpath:applicationContext.xml")