Spring常用注解!!!

pom.xml:


        
            org.springframework
            spring-context
            6.0.12
        
        
            org.slf4j
            slf4j-log4j12
            1.7.19
        
    

applicationContext.xml:




    
    
    
    

 log4j.properties:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

config.porperties:

name=小王
age=18

UserDaoImpl:

package com.by.dao;


import org.springframework.stereotype.Repository;

/**
 * 持久层实现类
 */
//@Repository("userDao")
@Repository //不配置默认为类名首字母小写
public class UserDaoImpl implements UserDao {

    @Override
    public void addUser() {
        System.out.println("insert into tb_user......");
    }
}

UserServiceImpl:

package com.by.service;

import com.by.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * 业务层实现类
 */
//@Service("userService")
@Service //不配置默认为类名首字母小写
//@Component
@Scope("prototype")
public class UserServiceImpl implements UserService {

    @Autowired //注入属性
    private UserDao userDao;
    @Value("${name}")
    private String name;
    @Value("${age}")
    private Integer age;

    @Override
    public void addUser() {
        System.out.println(userDao + "--" + name + "__" + age);
        userDao.addUser();
    }
}

总结:

IOC:

1.@Service:用于service层,@Service("userService")指定配置的id,@Service //不配置默认为类名首字母小写。
2.@Repository:用于dao层,@Repository("userDao")指定配置的id,@Repository //不配置默认为类名首字母小写。
3.@Component:用于配置与三层架构之外的类,也可用于其它几层,使用方法同上。
4.@Scope:用于配置bean的作用域范围,使用方法:@Scope("prototype")

DI:

1.@Autowired:用于注入属性, 
                @Autowired //注入属性
                 private UserDao userDao;

2.@Resource(name="userDao"),主要用于自定义类型

                @Autowired //注入属性
                 private UserDao userDao;

3.@value("${}"),主要用于基本数据类型和String类型,需要在config.properties文件中声明属性,在applicationContext.xml文件中加载config.properties文件   

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

你可能感兴趣的:(spring,java,后端)