Spring JDBC connection with the use of DI annotations

JDBC connection

1, when you configure the connection pool, you need to set four elements to the database connection, you can write directly to death, can also be used to introduce properties file

2, prior to the introduction to note:

  First it should be introduced namespace context

    Configuring maven dependence

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38 </version>
        </dependency>

  Configuring connection pool

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--配置德鲁伊-->
    <bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource"
     init-method="init" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
    </bean>
</beans>

  After the introduction and use placeholders profile

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!- ->
       default is the path from classes to start lookingthe introduction of property profiles, location: load the configuration file from any location attribute
    
    <context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>

    <!--配置德鲁伊-->
    <bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource"
     init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
</beans>

  db.properties follows

driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///mybatis
username=root
password=1234

Integrated Case

1, the code structure

  2, Code Contents

@Setter@Getter@AllArgsConstructor@NoArgsConstructor@ToString
public class User {
    private String id;
    private String username;
    private String password;
    private String date;
    private String salary;
}
User
@Controller
public class UserController {
    @Autowired
    private IUserService userService;

    public void service(){
        String username="rose";
        String password="123";
        String id =null;
        String date="2018-10-10";
        String salary ="2000";
        User user = new User(id,username,password,date,salary);
        userService.save(user);
    }
}
UserController
@Repository
public class UserDaoImpl implements IUserDao {
    @Autowired
    private DataSource dataSource;
    public void save(User user) {
        try {
            Connection connection = dataSource.getConnection();
            String sql = "insert into user values(null,?,?,?,?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getDate());
            ps.setString(4,user.getSalary());
            ps.execute();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
UserDaoImpl
public interface IUserDao {
    void save(User user);
}
UserDao
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserDao userDao;

    public void save(User user) {
        userDao.save(user);
    }
}
UserService
public interface IUserService {
    void save(User user);
}
IUserService
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class App {

    @Autowired
    private ApplicationContext context;
    @Test
    public void test(){
        UserController userController = context.getBean(UserController.class);
        userController.service();
    }
}
App test class
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!- ->
       default is the path from classes to start lookingthe introduction of property profiles, location: load the configuration file from any location attribute
    
    <context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>

    <!--配置德鲁伊-->
    <bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource"
     init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>

    <bean id="userController" class="com.test.test_anli.controller.UserController">
        <property name="userService" ref="userService"/>
    </bean>
    <bean id="userService" class="com.test.test_anli.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"/>
    </bean>
    <bean id="userDao" class="com.test.test_anli.dao.impl.UserDaoImpl">
        <property name="dataSource" ref="dateSource"/>
    </bean>
</beans>
applicationContext.xml

These codes have been used for annotation mode, you can delete the comment, the @autowired instead @setter, use xml file

DI Notes

1, used to complete the annotation in Spring DI operation, we call annotation automatic assembly, there are two use ..

  One: the Spring Framework itself provides annotations: @Autowired

  Two: Use JavaEE specifications provided by Notes: @Resource exactly the same function

2, Autowired and Qualifier Tags:

  1. Spring allows labels @Autowired automatically by the attributes required to find out the object from Spring container, and injection (provided) to the attribute.

  2. The third-party programs: Before Spring3.0, need to manually configure @Autowired annotation parser; <context: annotation-config />

    Beginning in Spring3.0, Spring will automatically join parser for @Autowired label.

  3. @ Autowired label on the field or setter methods.

  4. @ Autowired may be simultaneously injected into a plurality of attribute objects.

   public void setXxx(OtherBean1 other1,OtherBean2 other2) {}

  5. Spring @Autowired important object of tags can be injected into the built-in, such as BeanFactory, ApplicationContext.                 

   @RunWith(SpringJUnit4ClassRunner.class)

   @ContextConfiguration public class SpringTest { @Autowired private ApplicationContext ctx; }

  @Autowired label must be able to find the corresponding object 6. By default, otherwise an error. However, you can use required = false to avoid this problem:

   @Autowired(required=false)

  7. @ Autowired find bean ways:

   (1) First, in accordance with the type of dependent objects to find, if not found, the default will complain; if a match is found the object, direct injection;

   (2) If multiple matches are found in the type Spring context (or 2 or more), and then look for by name, if no match is being given;

   (3) may be predetermined dependent objects to find in accordance with the type of the bean by using id + @Qualifier ( "otherBean") tags;

 

Guess you like

Origin www.cnblogs.com/xfdhh/p/11483164.html