Annotations commonly used in Spring (absolutely innocent)

catalogue

 

1, Common Spring annotations - IOC related

1. Used to create objects

2. Used to change the scope of action

3. Life cycle related​​​​​​​

2, Load annotations for third-party resources

1,@Bean

2. What is the difference between @ bean ? and @ component ??

3. Integrating MyBaitis with annotations

4. Integrating JDBC with annotations

5. Summary

3, Annotations for injecting data - DI related annotations

1. Reference type attribute injection

2. Common type attribute injection

 

1, Common Spring annotations - IOC related

1. Used to create objects

The function of < bean id = "" class = "" > tag in xml configuration is the same. Annotations are placed on classes

@Component  ==> Generic type
@Controller ==> Control layer
@Service    ==> Business layer
@Repository ==> Data access layer / Persistent layer

Function: make the object of our three-tier architecture clearer, make the development more standardized and conform to the three-tier architecture!

Details: if there is only one attribute to be assigned in the annotation, the value attribute can not be written. The default is the class name, with the first letter in lowercase

How are the four annotations different? Can I mix it up?

  • The functions of these four annotations are the same, but we don't recommend mixing them!
  • Reason: three tier architecture: --- use @ Controller @ Service @ Repository respectively
  • @Component -- use @ component outside the three-tier architecture, mainly for entity classes

2. Used to change the scope of action

The function is the same as that of the scope attribute of the < bean > tag in xml configuration

@Scope

effect:
    appoint bean Scope of action.

Properties:
    value: Specifies the value of the range. 
    Value:`singleton` `prototype` `request` `session` `globalsession`  
    Common values: single example singleton    Multiple cases prototype

3. Life cycle related

The function is the same as that of init method and destroy method attributes of < bean > tag in xml configuration

    @PostConstruct  -- The annotation is placed on the method; Execute when initializing object
    @PreDestroy   -- The annotation is placed on the method; Execute on object destruction

 

2, Load annotations for third-party resources

 

1,@Bean

//@Bean is used to store the return value of the current method as a bean object in the ioc container of spring. You can specify the id of the bean.

@Bean("dataSource")
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

 

2. What is the difference between @ bean ? and @ component ??

@The bean annotation {is written on the method, and the return value of the method is stored in the spring container;

@component is written on the class. Create an object for the current class and store it in the spring container!

 

3. Integrating MyBaitis with annotations

public class MyBatisConfig {

    /*  spring Object for creating connection after integrating mybatis
        <bean class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="typeAliasesPackage" value="com.jing.domain"/>
        </bean>*/
    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setTypeAliasesPackage("com.jing.domain");
        ssfb.setDataSource(dataSource);
        return ssfb;
    }

    /* Load the scan of mybatis mapping configuration and manage it as a spring bean
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.jing.dao"/>
    </bean>*/
    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.jing.dao");
        return msc;
    }
}

 

4. Integrating JDBC with annotations

/**
 *     Load druid resource
 *     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
 *         <property name="driverClassName" value="${jdbc.driver}"/>
 *         <property name="url" value="${jdbc.url}"/>
 *         <property name="username" value="${jdbc.username}"/>
 *         <property name="password" value="${jdbc.password}"/>
 *     </bean>
 */

public class JDBCConfig {
    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Bean("dataSource")
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

 

Then you can configure class import

 

@Configuration
@ComponentScan("com.jing")
@PropertySource("classpath:jdbc.properties")
@Import({JDBCConfig.class,MyBatisConfig.class})
public class SpringConfig {
}

@Configuration specifies the current class as a configuration class, which is passed in as a parameter when creating a container! (instead of applicationContext.xml)


@ComponentScan("com.jing") is used to specify the packages that spring will scan when initializing the container
Compare the configuration of xml file: < context: component scan base package = "com. Jing" / >


@PropertySource("classpath:jdbc.properties") loads JDBC Properties configuration file
Compare the configuration of xml file: < context: Property placeholder location = "classpath: JDBC. Properties" / >


@Import({JDBCConfig.class,MyBatisConfig.class}) loads into the core configuration

 

If using junit test

Use @ RunWith # and @ ContextConfiguration

//Set up Spring specific class loader
@RunWith(SpringJUnit4ClassRunner.class)
//Set the configuration corresponding to the loaded Spring context
@ContextConfiguration(classes = SpringConfig.class)
public class UserTest {
    @Autowired
    private UserService userService;

    @Test
    public void test01(){
        int size = userService.findAll().size();
        Assert.assertEquals(8,size);
    }
}

 

5. Summary

Through the above code implementation, we can see that using third-party annotations will be more cumbersome than writing xml files, so it is generally recommended

Semi annotation + semi xml to develop

 

3, Annotations for injecting data - DI related annotations

The function is the same as that of the < property > tag in the < bean > tag in the xml configuration. Note: it is on the member variable

 

1. Reference type attribute injection

@Autowired /*Automatic injection by type,
            If multiple types are the same, judge whether the bean id is consistent with the variable name,
            If they are consistent, the corresponding injection will be performed, that is, first according to the type and then according to the variable name!*/

@Qualifier /*On the basis of automatic injection by type, it is injected according to the id of the Bean
             It cannot be used independently when injecting fields,
             Must be used with @ Autowire; However, it can be used independently when injecting method parameters*/
    For example:       @Autowired
                @Qualifier("userDao")
                private UserDao userDao;

@Resource  /*Inject directly according to the id of the bean. Only other bean types can be injected.

            @Resource It's jdk1 8, in jdk1 After 9, it is removed into the expansion module,
            So if you want to inject data with @ Resource annotation
            Please use 1.6-1.8 and below JDK equivalent 

            @Resource  = @Autowired + @Qualifier 
                            
            @Autowired , @Qualifier It is in the Spring framework*/

    For example:  @Resource(name = "userDao")
            private UserDao userDao;

The above three are to assign a value to the reference variable -- ref

2. Common type attribute injection

@Value      /* Assign a value to the attribute for the basic data type > > value
               You can use the writing method of spiel: ${expression}, which is the el expression of spring */

For example:
        @Value("Zhang San")
        private String name;


        @Value("${username}")
        private String username;

 

 

Keywords: Java Maven Spring

Added by dlgilbert on Wed, 02 Feb 2022 10:59:40 +0200