26 Eylül 2017 Salı

JndiObjectFactoryBean Sınıfı

Giriş
JNDI nesnesini Spring Bean haline getirir.

Kullanım
Şöyle yaparız
<bean id="dbServiceBean" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="#{T(com.foo.DbAccessUtils).DB_SERVICE_BEAN_JNDI}" />
  <property name="proxyInterface" value="com.foo.IDbServiceLocal" />
</bean>
setLookupOnStartup metodu
Örnek
Lazy init için XML ile şöyle yaparız.
<jee:jndi-lookup id="datasource" jndi-name="java:/comp/env/jdbc/Tomcat8Database"
  destroy-method="close" expected-type="javax.sql.DataSource" lookup-on-startup="false"
  proxy-interface="javax.sql.DataSource"/>

24 Eylül 2017 Pazar

SpringSecurity SecurityContextLogoutHandler Sınıfı

Giriş
SecurityContextHolder aracılığı ile SecurityContext nesnesi üzerinde değişikli yapabilmeyi sağlar

logout metodu
Şöyle yaparız
@GetMapping("/logout")
public String getLogoutPage(HttpServletRequest request,
  HttpServletResponse response){

  Authentication authentication = SecurityContextHolder.getContext()
    .getAuthentication();
  if (authentication != null)
    new SecurityContextLogoutHandler().logout(request, response, authentication);

  return "redirect:/login";
}

22 Ağustos 2017 Salı

SpringBatch JdbcCursorItemReader Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.database.JdbcCursorItemReader;
constructor
Şöyle yaparız.
JdbcCursorItemReader<Foo> databaseReader = new JdbcCursorItemReader<>();
setDataSource metodu
Şöyle yaparız.
DataSource dataSource = ...;
databaseReader.setDataSource(dataSource);
setRowMapper metodu
Şu satırı dahil ederiz.
import org.springframework.jdbc.core.BeanPropertyRowMapper;
Şöyle yaparız.
databaseReader.setRowMapper(new BeanPropertyRowMapper<>(Foo.class));
setSql metodu
Örnek
Şöyle yaparız.
private static final String QUERY_FIND_STUDENTS =
        "SELECT " +
            "email_address, " +
            "name, " +
            "purchased_package " +
        "FROM STUDENTS " +
        "ORDER BY email_address ASC";

databaseReader.setSql(QUERY_FIND_STUDENTS);
Örnek
Şöyle yaparız.
@Autowired
public DataSource dataSource;


@Bean
public JdbcCursorItemReader<User> reader() {
  JdbcCursorItemReader<User> reader = new JdbcCursorItemReader<User>();
  reader.setDataSource(dataSource);
  reader.setSql("SELECT id,name FROM employee");
  reader.setRowMapper(new UserRowMapper());
  return reader;
}

public class UserRowMapper implements RowMapper<User> {

  @Override
  public User mapRow(ResultSet rs, int rowNum) throws SQLException {
    User user = new User();
    user.setId(rs.getInt("id"));
    user.setName(rs.getString("name"));

    return user;
  }

}