我想知道我是否正确地注释了这些类,因为我是注释的新手:
Country.java
@Component
public class Country {
private int countryId;
private String countryName;
private String countryCode;
/**
* No args constructor
*/
public Country() {
}
/**
* @param countryId
* @param countryName
* @param countryCode
*/
public Country(int countryId, String countryName, String countryCode) {
this.countryId = countryId;
this.countryName = countryName;
this.countryCode = countryCode;
}
//getters and setters
}
CountryDAO.java
@Repository
public interface CountryDAO {
public List<Country> getCountryList();
public void saveCountry(Country country);
public void updateCountry(Country country);
}
JdbcCountryDAO.java
@Component
public class JdbcCountryDAO extends JdbcDaoSupport implements CountryDAO{
private final Logger logger = Logger.getLogger(getClass());
@Autowired
public List<Country> getCountryList() {
int countryId = 6;
String countryCode = "AI";
logger.debug("In getCountryList()");
String sql = "SELECT * FROM TBLCOUNTRY WHERE countryId = ? AND countryCode = ?";
logger.debug("Executing getCountryList String "+sql);
Object[] parameters = new Object[] {countryId, countryCode};
logger.info(sql);
//List<Country> countryList = getJdbcTemplate().query(sql,new CountryMapper());
List<Country> countryList = getJdbcTemplate().query(sql, parameters,new CountryMapper());
return countryList;
}
CountryManagerIFace.java
@Repository
public interface CountryManagerIFace extends Serializable{
public void saveCountry(Country country);
public List<Country> getCountries();
}
CountryManager.java
@Component
public class CountryManager implements CountryManagerIFace{
@Autowired
private CountryDAO countryDao;
public void saveCountry(Country country) {
countryDao.saveCountry(country);
}
public List<Country> getCountries() {
return countryDao.getCountryList();
}
public void setCountryDao(CountryDAO countryDao){
this.countryDao = countryDao;
}
}
答案 0 :(得分:20)
这个答案应该清楚一点:What's the difference between @Component, @Repository & @Service annotations in Spring?
你应该知道的其他事情:
您的实体和接口不需要任何注释。实际上,@ Component和其他派生注释只是意味着你在运行时声明一个Spring bean。例如,
@Component
public class MyComponent { ... }
默认情况下会在Spring的上下文中添加一个名为“myComponent”的bean。 Spring bean默认是单例,表示真实的实例化对象 因此,将实体或接口声明为Spring bean是没有意义的。
管理员在语义上与服务相同,因此您应该使用@Service注释它们。
以下是您的代码应该如何:
// No annotation
public class Country {
和
// No annotation
public interface CountryDAO {
和
@Repository
public class JdbcCountryDAO extends JdbcDaoSupport implements CountryDAO {
和
// No annotation
public interface CountryManagerIFace extends Serializable{
和
@Service
public class CountryManager implements CountryManagerIFace{
@Autowired
private CountryDAO countryDao;
注意:我很少在代码中使用@Component,因为@Controller(表示层),@ Service(服务层)和@Repository(dao层)覆盖了我的主要Spring bean需求。